Suppose you have a C++ class Foo, and you say:
Foo* foos = new Foo[SOME_CONSTANT];
memset(foos, 0, sizeof(Foo)*SOME_CONSTANT);
//or the bzero equivalent
and that Foo has a data member Bar* barPtr. Will the above operation guarantee that
barPtr will be NULL? (i.e. zero). I ran into a case in gdb where this didn’t hold for memset and I’m curious why.
I know the above is probably bad practice but I’m asking for curiosity.
I realized that I had an extra , i was doing sizeof(Foo)*SOME_CONSTANT in the memset…
On the one hand, it is implementation-defined.
memsetorbzerowill fill the pointer value with all-zero bit pattern, which is not guaranteed to be a physical representation of null pointer on the given platform. It is not even guaranteed to produce a valid pointer value, meaning that you might end up with so called trap representation, which triggers undefined behavior when accessed.On the other hand,
bzerois (or used to be) a part of POSIX specification. If memory serves, POSIX requires (or at least used to require) null-pointers to be represented by all-zero bit pattern, meaning that on POSIX systems it will indeed set a pointer to null.But again, the guarantee given by POSIX is just an example of an implementation-specific property mentioned in the first part of my answer. The language (C or C++) provides no such guarantees.