1

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?

Julius
  • 1,155
  • 9
  • 19
  • "`memset(mem + 100, 0, 20); // is this even necessary?`" --> Yes. – David C. Rankin Apr 15 '20 at 20:45
  • 1
    Please, also note that `mem = realloc(mem, 120);` is not a good idea. See e.g. https://stackoverflow.com/questions/38213123/is-it-good-coding-practice-to-assign-the-address-returned-by-realloc-to-the-sa – Bob__ Apr 15 '20 at 20:56
  • Your test proves nothing. The data was still zeros from the `calloc()`. – user207421 Apr 15 '20 at 22:51

1 Answers1

5

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.

kaylum
  • 13,833
  • 2
  • 22
  • 31
  • Good answer; UV. Minor: "`realloc` does not touch those bytes." is more like the C spec's "Any bytes in the new object beyond the size of the old object have indeterminate values.". An implementation might touch the new bytes, might not, might zero them, etc. What is important is that they are _indertminate_. The subtilty here is that `realloc()` is not required to not touch them. I could see a security feature that scrubs memmory. – chux - Reinstate Monica Apr 15 '20 at 22:27
  • 1
    @chux-ReinstateMonica Very good point. I have updated with what you have pointed out. – kaylum Apr 15 '20 at 22:30