calloc 后的 realloc 是否会清零字节?

Does a realloc after a calloc zero out bytes?

我一直在阅读“”。现在我想知道如果块较大,realloc 后跟 calloc 是否会将新字节清零。

愚蠢的例子:

#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?
}

我已经测试过了,好像是归零了-但我不确定是不是总是这样?

不,realloc 不会将新字节清零。它在 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.

对此评论:

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

这不是决定性的测试。如前所述,realloc 未定义为将这些字节初始化为任何特定值。因此不能保证字节为零(或任何其他值)并且永远不应依赖。