Re: NULL and zeros



Christopher Layne said:

Richard Heathfield wrote:

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.

How is,

1. The first unsafe? (presuming the rest of the members are explicitly
initialized as well)

You forgot to check the result of the malloc call before relying on it.


2. The latter not result in a zero-filled struct?

Even assuming the calloc call succeeds (which is not a given), only those
members of the struct that are integer types are guaranteed to be given 0
values.

In most calloc()
implementations I've seen, they're just malloc() + memset().

And that's why. All calloc gives you is a block of memory with all-bits-zero
(for which memset is a fairly reasonable implementation technique). But
all-bits-zero doesn't necessarily mean "zero value", for pointer types and
floating point types.

--
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)
.



Relevant Pages

  • Re: NULL and zeros
    ... The latter doesn't guarantee you a zero-filled struct, ... The first unsafe? ... In most calloc() ...
    (comp.lang.c)
  • Re: variable length array
    ... a bad habit I got from using a bad compiler that gave ... Does it guarantee that memory is zeroed? ... that anyway you might as well just use malloc rather than calloc. ...
    (comp.lang.c)