Search code examples
c++visual-studio-2013dynamic-memory-allocationdelete-operator

Heap Corruption detected


This is the way that i have alocated the memory.

Expression = new char[MemBlock.length()];
VarArray = new char[Variables.length()];
for (unsigned int i = 0; i < MemBlock.length(); i++)
{
    Expression[i] = MemBlock.at(i);
}
Expression[MemBlock.length() + 1] = NULL;
for (unsigned int i = 0; i < Variables.length(); i++)
{
    VarArray[i] = Variables.at(i);
}
VarArray[Variables.length() + 1] = NULL;

when i try to delete it i get the error...

Logic::~Logic(){
delete[] VarArray;  -> happens on this line.
VarArray = NULL;
delete[] Expression;
Expression = NULL;
}

in the entire code i dont not make any changes to the new array yet it tells me i hame some currpution, i cant pin point the problem , any help would be great.


Solution

  • VarArray[Variables.length() + 1] = NULL;

    accesses memory you do not own since this array is allocated thus:

    VarArray = new char[Variables.length()];

    The final element in this array has index Variables.length() - 1.

    Running this in a debugger ought be be instructive. Some static analysis tools (eg. lint) would highlight this misuse, I believe.

    You could also consider using boost::scoped_array or similar to remove the need for manual deletion. A good lesson to learn early on for C++ is to adopt RAII instead of manual memory management, wherever you can.