[英]What is the trouble with this code? Why is it showing: Debug assertion failed! _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)?
What is wrong in the code? 代码有什么问题?
What change should I make in the code to make it defensive? 我应该对代码进行哪些更改以使其具有防御性?
#ifndef _ARRAY_H_
#define _ARRAY_H_
class Array
{
private:
int * m_ArrayContainer;
public:
Array();
void AllocateMemoryOfSize(int size);
void DeallocateMemory();
void SetElementsIntoTheIndex(int index, int value);
int GetElementFromIndex(int index);
int operator [] (int index);
~Array();
};
#endif
#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();
}
}
The destructor calls DeallocateMemory()
for the second time and that leads to delete[]
being called for the second time with the same address which triggers undefined behavior. 析构函数第二次调用
DeallocateMemory()
,并导致第二次调用delete[]
并使用相同的地址触发未定义的行为。 To guarg against this you should change 为了反对这一点,你应该改变
void Array::DeallocateMemory()
{
delete [] this->m_ArrayContainer;
this->m_ArrayContainer = 0;
}
so that when the destructor is called and it calls DeallocateMemory()
a null pointer is delete[]
d which is a no-op. 因此,当析构函数被调用并调用
DeallocateMemory()
,空指针为delete[]
d,它是一个空操作。
Btw you should at least prohibit copy constructor and operator=
in your class by declaring them private and leaving unimplemented - your class doesn't support memberwise copying. 顺便说一句,您至少应该在类中声明复制构造函数和
operator=
私有,并保留它们未实现的状态-您的类不支持成员级复制。
Because in each iteration of the loop you call delete[]
twice on the same allocated array. 因为在循环的每次迭代中,您在同一分配的数组上两次调用
delete[]
。 Once via an explicit call to DeallocateMemory
and once via the call in the destructor of Array
. 一次是通过对
DeallocateMemory
的显式调用,一次是通过Array
的析构函数中的调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.