在删除行的正常块之后检测到堆损坏
heap corruption detected after normal block at delete row
你好,我调用函数"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
}
问候
相关文章:
- 检测到堆损坏:在正常块 c++ 动态 2D 数组之后
- 删除字符串后C++检测到堆损坏
- 检测到堆损坏(字符串导致堆损坏)|C++
- 在C++中检测到堆损坏错误
- C++ 内存损坏检测
- 如何修复检测到堆损坏:正常阻止后
- 在复制 delete[] 数组后在 C++ 中检测到堆损坏
- 从检测到 glibc 正常退出 - malloc():内存损坏
- 编译器如何检测内存损坏
- 排序程序的错误(检测到堆损坏)
- 正常块错误后检测到的堆损坏
- C++ 删除数组时检测到堆损坏
- 调试错误,在C++中检测到堆损坏
- 检测到堆损坏(类方法)
- 在普通块(#164)之后检测到堆损坏
- jemalloc未检测到内存损坏
- 检测到合并排序堆损坏
- 错误: *** 检测到 glibc *** w5:双重释放或损坏(快速顶部):
- 检测到堆损坏:在正常块(#62)之后
- 在Windows上立即检测到堆损坏错误.如何