在删除行的正常块之后检测到堆损坏

heap corruption detected after normal block at delete row

本文关键字:检测 损坏 之后 常块 删除行      更新时间:2023-10-16

你好,我调用函数"add"3次,在第三次调用中,它给了我这个错误:"在正常块之后检测到堆损坏"

头文件:

template <class T>  
class Array
{
private:    
   T* myArray;
   int size;
public:     
   Array(); 
   Array(int _size);        
   void add(T object);  
   void remove(T Object);   
   int getSize();   
   ~Array();
};

类中的函数"add"Array:

    template <class T>
void Array<T>::add(T object)
{
    T* tempArr = new T(size + 1);
    for (int i = 0; i < size; i++)
    {
        tempArr[i] = myArray[i];
    }
    tempArr[size] = object;
    size++;
    if (myArray != NULL)
        delete[] myArray;    <------- "in this line its give me the error in the third time"
    myArray = tempArr;
}

此行

T* tempArr = new T(size + 1);

没有分配数组。它为分配一个T,并使用size + 1对其进行初始化。

你想要的是(注意[]):

T* tempArr = new T[size + 1];

1)正如评论中所说的那样,您应该使用与您使用新相对应的删除运算符

在添加功能中:

template <class T>
void Array<T>::add(T object)
{
    T* tempArr = new T[size + 1];  // with this, you use new[] ...
    for (int i = 0; i < size; i++)
    {
        tempArr[i] = myArray[i];
    }
    tempArr[size] = object;
    size++;
    if (myArray != NULL)
        delete[] myArray;          // so you should use delete[] here.
    myArray = tempArr;
}

2) 检查myArray在构造函数中是否初始化为NULL,因为C++中没有为指针分配默认值。

在构造函数中:

template <class T>
Array<T>::Array(void)
{
   myArray = NULL;  // must do it, otherwise it will get some memory junk as value
}

问候