C++ 这个代码有什么问题?为什么显示:调试断言失败_块类型是否有效(pHead->;nBlockUse)?

C++ 这个代码有什么问题?为什么显示:调试断言失败_块类型是否有效(pHead->;nBlockUse)?,c++,memory-leaks,visual-studio-debugging,C++,Memory Leaks,Visual Studio Debugging,代码中有什么错误 我应该在代码中做什么更改以使其具有防御性 数组.h Array.cpp #包括“Array.h” #包括 数组::数组() { 此->m_ArrayContainer=NULL; } void数组::AllocateMemoryOfSize(整数大小) { 此->m_ArrayContainer=new int[size]; } void数组::DeallocateMemory() { 删除[]此->m_ArrayContainer; } void数组::SetElements

代码中有什么错误

我应该在代码中做什么更改以使其具有防御性

数组.h Array.cpp
#包括“Array.h”
#包括
数组::数组()
{
此->m_ArrayContainer=NULL;
}
void数组::AllocateMemoryOfSize(整数大小)
{
此->m_ArrayContainer=new int[size];
}
void数组::DeallocateMemory()
{
删除[]此->m_ArrayContainer;
}
void数组::SetElementsIntoTheIndex(int索引,int值)
{
此->m_ArrayContainer[索引]=值;
}
int数组::GetElementFromIndex(int索引)
{
返回此->m_ArrayContainer[索引];
}
int数组::运算符[](int索引)
{
返回此->m_ArrayContainer[索引];
}
数组::~Array()
{
此->解除分配内存();
}
Main.cpp
#包括
#包括“Array.h”
int main()
{   

对于(int i=0;i,因为在循环的每次迭代中,在同一个分配的数组上调用两次
delete[]
。一次通过显式调用
DeallocateMemory
,一次通过调用
数组的析构函数
,析构函数调用
DeallocateMemory()
第二次,这将导致使用触发未定义行为的相同地址第二次调用
delete[]
。为避免这种情况,您应该更改

void Array::DeallocateMemory()
{
    delete [] this->m_ArrayContainer;
    this->m_ArrayContainer = 0;
}
因此,当调用析构函数并调用
DeallocateMemory()
时,空指针是
delete[]
d,这是一个不可操作的指针


BTW,你应该至少禁止复制构造函数和<代码>运算符=/COD>在你的类中声明它们不存在,你的类不支持成员复制。

自从你的编辑,TL;博士尝试发布一个最小的,可编译的例子来显示错误。d可能只是使用std::vector。这个解决方案是正确的。不要放弃。试着找出问题所在。在数组类中进行一些索引检查。@BROY你介意公布你解决问题的方法吗?你使用了sharptooth建议的方法吗?
#include "Array.h"
#include <iostream>

Array :: Array()
{
    this->m_ArrayContainer = NULL;
}

void Array :: AllocateMemoryOfSize(int size)
{
    this->m_ArrayContainer = new int[size];
}

void Array :: DeallocateMemory()
{
    delete [] this->m_ArrayContainer;
}

void Array :: SetElementsIntoTheIndex(int index, int value)
{
    this->m_ArrayContainer[index] = value;
}

int Array :: GetElementFromIndex(int index)
{
    return this->m_ArrayContainer[index];
}

int Array :: operator [] (int index)
{
    return this->m_ArrayContainer[index];
}

Array :: ~Array()
{
    this->DeallocateMemory();
}
#include <iostream>
#include "Array.h"

int main()
{   
for(int i=0 ; i<250 ; i++)
{
    Array array1;
    array1.AllocateMemoryOfSize(3);
    array1.SetElementsIntoTheIndex(0, 10);
    array1.SetElementsIntoTheIndex(1, 10);
    array1.SetElementsIntoTheIndex(2, 10);

    /*array1.SetElementsIntoTheIndex(0, NULL);
    array1.SetElementsIntoTheIndex(1, NULL);
    array1.SetElementsIntoTheIndex(2, NULL);*/

    array1.DeallocateMemory();
}
}
void Array::DeallocateMemory()
{
    delete [] this->m_ArrayContainer;
    this->m_ArrayContainer = 0;
}