Search code examples
cmemoryallocationrealloccalloc

Does a realloc after a calloc zero out bytes?


I have been reading "How to realloc some memory allocated using calloc?". Now I am wondering whether a realloc followed by a calloc will zero out new bytes if the block is larger.

Silly example:

#include <stdlib.h>
#include <string.h>

int test() {
  char *mem;

  mem = calloc(100, 1);
  mem = realloc(mem, 120);
  memset(mem + 100, 0, 20); // is this even necessary?
}

I have tested it, and it seems to be zeroed out - but I am not sure whether it is always the case?


Solution

  • No, realloc does not zero out the new bytes. It says so in the realloc manual:

    The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is larger than the old size, the added memory will not be initialized.

    To this comment:

    I have tested it, and it seems to be zeroed out

    That's not a conclusive test. As stated, realloc is not defined to initialise those bytes to any particular value. So there is in no guarantee that the bytes will be zero (or any other value) and should never be relied on.