将重新分配的内存设置为0是常见的做法吗? [英] Is it common practice to memset reallocated memory to 0?

查看:103
本文介绍了将重新分配的内存设置为0是常见的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一本C书中,我发现了一个示例,该示例实现了一个动态调整大小的数组,该代码(简化了):

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);

来源:学习"The C Way" –第34章

我很惊讶memset应该在这里实现什么,但是后来我了解到它是用来归零"重新分配的内存的.

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.

我用谷歌搜索以找出是否是realloc之后我应该做的,并找到了关于此的stackoverflow答案:

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:

可能无需执行memset […]

但是,即使您想将其归零以使一切都很好",或者真的需要新的指针为NULL:C标准并不保证all-bits-zero是空指针常量(即NULL),所以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), so memset() isn't the right solution anyway.

来源:如何在重新分配后将新内存清零

建议的解决方案而不是memset是使用for循环将内存设置为NULL.

The suggested solution instead of memset is then to use a for loop in order to set the memory to NULL.

所以我的问题是,因为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?

推荐答案

所以我的问题是,因为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 doesn't initialize values of the newly allocated memory segment.

因此,如果您打算读取该(未初始化的)内存值,则需要初始化该内存.因为从未初始化的内存中读取值将触发未定义的行为.

So it is needed to initialize the memory if you are planning to read values of that (uninitialized) memory. Because reading values from that uninitialized memory will trigger undefined behaviour.

顺便说一句,使用realloc的安全方法(因为它可能会失败)是:

By the way, safe way to use realloc (since it can fail) is:

  // 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;
    }
  }

这篇关于将重新分配的内存设置为0是常见的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆