"Do I still need to set ptr
to NULL
if I use memset()
earlier?"
If you want your program to be fully standard-compliant, then yes, as memset()
set each byte to 0
, which is different to setting NULL
to a pointer. (Assuming ptr
is equivalent to p
inside of the structure sth
).
Quote from the current C standard ISO:IEC 9899:2018 (C18), Section 7.22.3.5/2 - The calloc function:
"The space is initialized to all bits zero. 302)"
"302 - Note that this need not be the same as the representation of floating-point zero or a null pointer constant."
"Since I have used memset()
, do I still need to write A, B, C"?
A.
is redundant, as soon as t
is not an object of floating-point type as those can have a floating-point zero value, which may not have all bits set to 0
. If t
were f.e. of type float
or double
A.
would be useful and appropriate to be standard conform.
B.
and C.
are appropriate, since according to the standard setting each byte to 0
does not necessarily also set the pointers to NULL
, if you explicitly want to have them assigned to NULL
(although it should on most systems).
Note that calloc()
might be more convenient and also faster in performance as it allocates memory and immediately initialize each bit of it to 0
:
struct sth *data = calloc(sizeof(*data));
But again here, p
and next
do not need to be NULL
.