May I set a pointer to NULL
portably (at least according to the POSIX standard) by memsetting it to zero? Or even memsetting the struct that contains it (where it becomes actually useful)?
Edit: POSIX specifies in stddef.h(0posix)
that NULL
shall be (void *) 0
, but that may not be enough to allow memset()
. I ignore if there are any other details that POSIX defines regarding this.
CodePudding user response:
In C, memset(&ptr, 0, sizeof(ptr))
is not necessarily the same as ptr=NULL
since the ISO/IEC 9899:1999 clause 17.7 paragraph 3 says that NULL
expands to an implementation-defined null pointer constant
Thus not necessarily an all-zero bit pattern.
Posix has not had a different guarantee than the C standard. However, the next revision draft says that
POSIX additionally guarantees that any pointer object whose representation has all bits set to zero, perhaps by memset() to 0 or by calloc(), will be interpreted as a null pointer.
Hence it seems that Posix will guarantee that memset(&ptr, 0, sizeof(ptr))
will have the same effect as ptr=NULL
(and this is mostly likely already the case on all existing implementations). However, the statements will not necessarily assign identical bit patterns to ptr
.
It is important to notice that the C standard (and Posix, also with the mentioned update) does not guarantee that the bit pattern of a null pointer is unique. Thus, in principle ptr=NULL
could assign a different bit pattern to ptr
than memset(&ptr, 0, sizeof(ptr))
as long as this bit pattern is also a null pointer.
The standard does guarantee (clause 6.3.2.3 paragraph 4) that
Any two null pointers shall compare equal.
Thus if ptr
and ptr2
are both null pointers, then ptr == ptr2
evaluates to true
. However, memcmp(&ptr, &ptr2, sizeof(ptr))
may not evaluate to 0
.