Re: char * cast on NULL?



Leonard den Ottolander wrote:
Hello Oswald,

On Sun, 2004-09-26 at 13:15, Oswald Buddenhagen wrote:

the outcome is, that it doesn't matter anywhere but when passing null
pointers through varargs. in all other cases it's about style, and taste
differs.


All in all it seems rather pointless to do this in only certain parts of
the code and at this point in time (approaching 4.6.1). If I need to
know the type of the last argument I can find it elsewhere.

That's almost always correct, due to function prototypes. But there's one exception to it: varargs. (As Oswald noted above)

Imagine a machine where pointers take 32 bit and ints take 16.

/* concat strings */
void concat(const char *first, ...);

Then you call:

/*1*/ concat ("first", "second", (char *) NULL);
/*2*/ concat ("first", "second", NULL);
/*3*/ concat ("first", "second", 0);

The function concat expects their arguments to be strings, but the compiler cannot guarantee that only strings are passed. So see what could happen: Let's say the address of first is 0xc0000040, the address of second is 0xc0000050. Then the arguments (grouped in 16 bits) could be:

/*1*/ [0xc000] [0x0040] [0xc000] [0x0050] [0x0000] [0x0000] [garbage...]
/*3*/ [0xc000] [0x0040] [0xc000] [0x0050] [0x0000] [garbage...]

Some systems actually #define NULL to be 0, so case /*2*/ could be either like /*1*/ or like /*3*/. But in case /*3*/, the string list is not terminated correctly, and a segmentation fault will occur.

Roland



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]