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();
}
}

The destructor calls
DeallocateMemory()for the second time and that leads todelete[]being called for the second time with the same address which triggers undefined behavior. To guarg against this you should changeso that when the destructor is called and it calls
DeallocateMemory()a null pointer isdelete[]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.