在一本 C 书中,我在实现动态调整数组大小的示例中找到了以下代码(简化):
void *contents = realloc(array->contents, array->max * sizeof(void *));
array->contents = contents;
memset(array->contents + old_max, 0, array->expand_rate + 1);
来源:Learn C The Hard Way – Chapter 34
我对 memset 在这里要实现的目标感到有点惊讶,但后来我明白它的用途是为了将重新分配的内存“清零”。
我在谷歌上搜索了一下,看看这是否是我在realloc
之后应该做的事情,并找到了一个关于此问题的stackoverflow答案:
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.
来源:How to zero out new memory after realloc
建议的解决方案是使用 for
循环来将内存设置为 NULL
,而不是使用 memset
。
所以我的问题是,因为 memset
并不一定意味着将值设置为 NULL
并且 for
循环解决方案似乎有点乏味 - 是真的需要设置新分配的内存吗?
最佳答案
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?
realloc
不会初始化新分配的内存段的值。
因此,如果您打算读取该(未初始化)内存的值,则需要初始化内存。因为从未初始化的内存中读取值将触发未定义的行为。
顺便说一句,使用realloc
的安全方法(因为它可能会失败)是:
// Since using realloc with size of 0 is tricky and useless probably
// we use below check (from discussion with @chux)
if (new_size == 0)
dosmth();
else
{
new_p = realloc(p, new_size);
if (new_p == NULL)
{
// ...handle error
}else
{
p = new_p;
}
}
关于c - memset 重新分配内存为 0 是常见做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32732449/