C++ malloc/realloc 奇怪的行为

C++ malloc/realloc weird behavior

我正在编写一个供自己使用的动态数组,我想用零预先设置。

template <class T>
dynArr<T>::dynArr()
{
rawData = malloc(sizeof(T) * 20); //we allocate space for 20 elems
memset(this->rawData, 0, sizeof(T) * 20); //we zero it!
currentSize = 20;
dataPtr = static_cast<T*>(rawData); //we cast pointer to required datatype.
}

这部分有效 - 通过循环迭代和取消引用 dataPtr 效果很好。零点。

然而,重新分配的行为(在我看来)至少有点奇怪。首先你要看重分配代码:

template <class T>
void dynArr<T>::insert(const int index, const T& data)
{

    if (index < currentSize - 1)
    {
        dataPtr[index] = data; //we can just insert things, array is zero-d
    }

    else
    {
        //TODO we should increase size exponentially, not just to the element we want

        const size_t lastSize = currentSize; //store current size (before realloc). this is count not bytes.

        rawData = realloc(rawData, index + 1); //rawData points now to new location in the memory
        dataPtr = (T*)rawData;
        memset(dataPtr + lastSize - 1, 0, sizeof(T) * index - lastSize - 1); //we zero from ptr+last size to index

        dataPtr[index] = data;
        currentSize = index + 1;
    }

}

很简单,我们将数据重新分配到索引+1,并将尚未归零的内存设置为0。

作为测试,我首先在这个数组的位置 5 上插入了 5。预期的事情发生了 - 0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

然而,插入其他东西,比如 insert(30,30) 会给我带来奇怪的行为:

0, 0, 0, 0, 0, 5, 0, -50331648, 16645629, 0, 523809160, 57600, 50928864, 50922840, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30,

什么鬼,我是不是没听懂? realloc 不应该考虑所有 20 个先前设置的内存字节吗?这是什么魔法。

问题 1:

您在 realloc 的调用中使用了错误的尺寸。将其更改为:

rawData = realloc(rawData, sizeof(T)*(index + 1)); 

如果 rawDataT* 类型,更喜欢

rawData = realloc(rawData, sizeof(*rawData)*(index + 1)); 

问题 2:

下面最后一个词不对

memset(dataPtr + lastSize - 1, 0, sizeof(T) * index - lastSize - 1); 

您需要使用:

memset(dataPtr + lastSize - 1, 0, sizeof(T) * (index - lastSize - 1));
                               //  ^^              ^^
                               // size      *  The number of objects 

问题 3:

使用

分配给dataPtr
dataPtr[index] = data;
当使用 mallocrealloc 获取内存时,

会出现问题。 malloc 函数族 return 只是原始内存。他们不初始化对象。 分配给未初始化的对象是所有非 POD 类型的问题。

问题 4:

如果 T 是带有虚拟成员函数的类型,使用 memset 清零内存很可能会导致问题。


解决所有问题的建议:

使用 newdelete 会好得多,因为你在 C++ 领域。

template <class T>
dynArr<T>::dynArr()
{
   currentSize = 20;
   dataPtr = new T[currentSize];
   // Not sure why you need rawData
}

template <class T>
void dynArr<T>::insert(const int index, const T& data)
{
   if (index < currentSize - 1)
   {
      dataPtr[index] = data;
   }

   else
   {
      const size_t lastSize = currentSize;
      T* newData = new T[index+1];
      std::copy(dataPtr, dataPtr+lastSize, newData);
      delete [] dataPtr;
      dataPtr = newData;
      dataPtr[index] = data;
      currentSize = index + 1;
   }
}

请注意,建议的更改仅在 T 是默认可构造的情况下才有效。

这也将解决上述问题 3 和 4。