Re: NULL and zeros



[much snippage]

Yevgen Muntyan said:

Christopher Layne wrote:

How is:

x->p = NULL;

Useless?

It is useless on given machines after x is allocated with calloc().

On some machines, that isn't the case. If you are excluding such machines,
you are in the wrong newsgroup.

If anything, it's more useful than:

x = calloc(1, sizeof *x);

In one case, I am provided with a zero-filled structure,
and then my job is to initialize it. And even when I am allocating
it myself, how is

x = malloc (sizeof (MyType));
x->p = NULL;

more useful than

x = calloc (1, sizeof (MyType));

Neither is useful. The latter doesn't guarantee you a zero-filled struct,
and the first is unsafe.

calloc() is actually more useful because you get well-defined object
content,

Only for integer types.

C standard guarantees that NULL == (void*) 0, doesn't it

No, it guarantees that NULL expands to an implementation-defined null
pointer constant. Since (void *) 0 is indeed an implementation-defined null
pointer constant, it will always compare equal with NULL, but NULL may be
defined as, say, 0.

But it still remains possible for null pointers on the target platform to be
represented by some other bit pattern. On platforms where that is the case,
the compiler must do some magic to ensure that, when it encounters 0 in a
pointer context, it interprets the 0 as "null pointer constant". Thus:

p = 0; /* p is a null pointer */
memset(&p, 0, sizeof p); /* p might now not be a null pointer! */

Otherwise you're sweating the small stuff and probably pre-optimizing
somewhere.

I am not optimizing anything. I don't like the *code* like following:

void do_init (MyStruct *obj)
{
obj->some_linked_list = NULL;
obj->other_linked_list = NULL;
obj->one_more_list = NULL;
obj->and_a_list_again = NULL;
}

given that obj is already zero-filled.

That is not a given, if it has been allocated via calloc. Anyway, it's
unnecessary. Just write a constructor:

MyStruct *MyStructCreate(void)
{
MyStruct blank = {0};
MyStruct *new = malloc(sizeof *new);
if(new != NULL)
{
*new = blank;
}
return new;
}

Easy.


--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
.