c++ - 动态数组中的未定义值

标签 c++

我正在阅读一本书来刷新我对数据结构和 C++ 的内存,并且我正在阅读实现一个位 vector 。在我的 Bitvector 类中,我有以下内容:

class BitVector
{
  public:
    Bitvector(int p_size)
    {
      m_array = 0;
      m_size = 0;
      Resize(p_size);
    }

    ~Bitvector()
    {
      if(m_array !=0)
        delete[] m_array;
      m_array = 0;
    }

    void Resize(int p_size)
    {
      unsigned long int* newvector = 0;
      if(p_size % 32 == 0)
        p_size = p_size / 32;
      else
        p_size = (p_size /32) + 1;

      newvector = new unsigned long int[p_size];

      if(newvector == 0)
        return;
      int min;
      if(p_size < m_size)
        min = p_size;
      else
        min = m_size;
      int index;
      for(index = 0;index < min; index++)
        newvector[index] = m_array[index];
      m_size = p_size;
      if(m_array != 0)
        delete[] m_array;
      m_array = newvector;
    }

    bool operator[](int p_index)
    {
      int cell = p_index / 32;
      int bit = p_index % 32;
      return (m_array[cell] & (1 << bit)) >> bit;
    }

    void Set(int p_index, bool p_value)
    {
      int cell = p_index / 32;
      int bit = p_index % 32;
      if(p_value == true)
        m_array[cell] = (m_array[cell] | (1 << bit));
      else
        m_array[cell] = (m_array[cell] & (~(1 << bit)));
    }
  protected:
    unsigned long int* m_array;
    int m_size;
};

当我在构造函数中初始化 newvector 指针时,没有初始化任何东西,所以数组处于未定义状态,对吗?因此,我正在使用 VS2010 并在进入代码时得到以下#:newvector 的 3452816845。我知道这表明目前还没有定义任何东西,但是对于 unsigned long int 来说这个值总是这样吗?这个范围有没有变化(这可能是 0)?我很好奇,因为在 [] 覆盖中,您将这个未定义的标识符与您移入的数字进行位连接。

最佳答案

您可以将数据的获取更改为:

newvector = new unsigned long int[p_size]();

获取初始化为0s的数据 block 。或者您可以手动初始化它,遍历数组或使用 memset(这适用于 POD 类型,但不适用于非 POD 类型,所以在使用它的地方要小心)。

关于这个值是否保证是那个,或者它是否是随机的,答案是它是未定义的。一些编译器在使用调试选项编译时会将数据初始化为分配时的已知值,并在释放期间重写以方便调试(如果你看到这个值,很可能你正在使用未初始化的内存/已经释放的对象),但你不能依赖就此而言,因为不同的编译器选项会改变效果。

在很多情况下,在 Release模式下,内 stub 本不会被修改。它甚至可能看起来是 0 初始化,因为出于安全原因,某些操作系统会在将它们提供给进程之前将内存页清空,但同样不要指望它,因为它只会保留第一次分配内存,以及稍后的内存分配Resize 可能不会获取新的内存页,但可能会产生一个先前分配和释放的 block ,其中包含在先前释放之前存储在那里的值。

如果你想让你的内存被初始化,你需要自己初始化。

关于c++ - 动态数组中的未定义值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4374987/

相关文章:

c++ - 定期调用的 c++ 函数

C++11:如果不为 std::thread 调用 join() 会发生什么

c++ - 常量重载 : Public-Private Lookup in C++ Class

c++ - 如何在用户输入特殊字符时退出程序

c++ - 忽略 xml 元素中的字符

c++ - 使用 C++ 在 Eclipse 中编译 <json/json.h>

c++ - cv::LUT() - 插值参数是什么?

c++ - 后缀运算符重载中虚拟参数的用途? C++

c++ - 复制构造函数中的初始化列表

c++ - 如何将二进制格式的 C++ 对象的 std::vector 保存到磁盘?