In a C book I found in an example for implementing a dynamically resizing array this code (simplified):
void *contents = realloc(array->contents, array->max * sizeof(void *));
array->contents = contents;
memset(array->contents + old_max, 0, array->expand_rate + 1);
Source: Learn C The Hard Way – Chapter 34
I was a bit surprised what memset
is supposed to achieve here, but then I understood it's used in order to "zero out" the reallocated memory.
I googled in order to find out, if this is what I'm supposed to do after a realloc
and found a stackoverflow answer regarding this:
There is probably no need to do the
memset
[…]But, even if you wanted to "zero it out so everything is nice", or really need the new pointers to be
NULL
: the C standard doesn't guarantee that all-bits-zero is the null pointer constant (i.e.,NULL
), somemset()
isn't the right solution anyway.
Source: How to zero out new memory after realloc
The suggested solution instead of memset
is then to use a for
loop in order to set the memory to NULL
.
So my question is, as memset
does not necessarily mean setting values to NULL
and the for
loop solution seems a bit tedious – is it really needed to set the newly allocated memory?