Consider the following initialization of an array of void
pointers:
#include <string.h>
void foo()
{
void * a[10];
memset(a, 0, sizeof a);
// ...
}
Is the array guaranteed to hold NULL pointers after the memset
call?
Consider the following initialization of an array of void
pointers:
#include <string.h>
void foo()
{
void * a[10];
memset(a, 0, sizeof a);
// ...
}
Is the array guaranteed to hold NULL pointers after the memset
call?
No, it's not guaranteed. Converting 0 to a pointer type is defined to produce a null pointer [6.3.2.3.3], but here you're setting the object representation of the pointer to all zero bytes. The standard doesn't specify the object representation of pointers, so an all-zero-byte pointer or may not be a null pointer.
I don't think your question needs to mention arrays, as asking whether p
is now a null pointer hinges on the same issue:
void *p;
memset(&p, 0, sizeof p);
No. As per C11 6.3.2.3 Pointers /3
, an integral constant or expression of zero will translate to the null pointer. However, the underlying representation of types is specified by 6.2.6
where /1
states:
The representations of all types are unspecified except as stated in this subclause.
Given there's nothing in that section pertaining to pointers, you cannot then assume that a null pointer is all zero bits, which is what you'll get from your memset()
call (neither signed char
nor unsigned char
are allowed to have padding bits and positive-zero is represented the same way in all possible encodings).
A safer way to do it is with:
void foo (void) {
void *a[10];
for (size_t s = 0; s < sizeof(a) / sizeof(*a); s++)
a[s] = 0;
}
You can use memset
if you know that all-zero-bits is the correct underlying representation of a null pointer in your implementation, but it won't be portable. That may not be an issue given the number of machines in active use that don't use that representation (very few if any). Just be aware of the possible ramifications.
If you put NULL
s in it then yes, it will hold NULL
s.
But you fill it with zeroes and 0
might happen to be the same as NULL
but there is no guarantee. It depends on the hardware architecture + operating system + compiler.
The short answer to your question is: NO.