C++malloc/realloc的奇怪行为



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

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

如果rawData属于T*类型,则首选

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函数系列只返回原始内存。它们不初始化对象。 分配给未初始化的对象是所有非 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。

最新更新