Alex Rivera | Logout

How to define NULL using #define

Asked 2010-02-24T11:40:52.163
9

I want to redefine NULL in my program such as

#define MYNULL ((void*)0)

But this definition is not working in the following statement:

char *ch = MYNULL;

Error : can not convert from void* to char *

What would be the best way to define NULL?

Edit
Report

2 Answers

0

In contrast to what some people state here, 0 is a perfectly valid definition for NULL in C. Thus you have to be careful when you give NULL as an argument to a variadic function, because it may be mistaken as the integer value 0, ending in non-portability.

http://c-faq.com/null/null2.html

BTW, the comp.lang.c FAQ is a highly recommended read for every C programmer. See for example here:

http://c-faq.com/null/null1.html

containing such gems of nearly-forgotten wisdom like "As mentioned above, there is a null pointer for each pointer type, and the internal values of null pointers for different types may be different." Which means that calloc or memset are NOT a portable initialization for pointers.

answered 2010-02-24T18:16:07.660
0
#define NULL 0 //for C

is the perfect definition in C

e.g.

char *ch = NULL ;
*ch++ ;// will cause error

it causes error since ch pointing to nothing while executing increment statement is known by compiler by seeing the value of pointer in LOOK-UP table to be 0

if u try to update this pointer then u are actually changing the contents of CODE region which start at 0 physical address. FOR that reason the first entry of page table prior to code region starts is kept empty

What exactly is the problem with getting your NULL from where you're supposed to?, i.e.,

#include <stddef.h>

or

#include <cstddef>

as alluded to in @Johannes Rudolph's answer, any trickery you do is not likely be very future proof in the face of things like nullptr etc.

EDIT: while stdlib (and many others) are mandated to include a NULL, stddef is the most canonical header [and has been for decades].

PS In general, it's just a bad idea to get involved in this sort of trickery unless you have a really good reason. You didnt expand on the thinking that led you to feeling the need to do this. If you could add some detail on that, it's likely to lead to better answers. Other people answering the question should have pointed this out in their answers too, but I guess does FGITW as FGITW does best :D

EDIT 2: As pointed out by @Yossarian: The single justification for doing this is if there isnt a NULL defined in an appropriately language-agnostic form elsewhere in your system. Naked compilers with no headers and/or if you're writing your own custom standard library from scratch are examples of such a circumstance. (In such a bare-bones scenario, I'd go with @lilburne's answer (be sure to use 0 as much as possible))

answered 2011-06-16T11:11:04.763

Your Answer