What is the trouble with this code? Why is it showing: Debug assertion failed! _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)?
-
29-10-2019 - |
Question
What is wrong in the code?
What change should I make in the code to make it defensive?
Array.h
#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
Array.cpp
#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();
}
Main.cpp
#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();
}
}
Solution
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. 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.
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.
OTHER TIPS
Because in each iteration of the loop you call delete[]
twice on the same allocated array. Once via an explicit call to DeallocateMemory
and once via the call in the destructor of Array
.