When I run the piece of code below once, it works properly. However, if I run it twice, then an error message of heap corruption poped up, and if I delete the statement, delete [] list, then it works find again. So what is the problem? what is the way to add the delete statement so I can free up the memory and the code works properly at the same time.
int main () {
int dataLength = 10;
int *ArrayOfNumber;
int *ArrayTemporary;
ArrayOfNumber = new int[dataLength];
ArrayOfNumber[0] = 10;
ArrayOfNumber[1] = 20;
ArrayOfNumber[2] = 30;
ArrayOfNumber[3] = 40;
ArrayOfNumber[4] = 50;
ArrayOfNumber[5] = 60;
ArrayOfNumber[6] = 70;
ArrayOfNumber[7] = 80;
ArrayOfNumber[8] = 90;
ArrayOfNumber[9] = 100;
for (int i = 0; i < dataLength; i++)
cout<<ArrayOfNumber[i]<<endl;
cout<< endl;
int element = 111;
int location;
for (int i = 0; i < dataLength; i++)
cout<<ArrayOfNumber[i]<<endl;
cout<< endl;
int x;
cin>> x;
return 0;
}
void InsertElement(int *&list, int &position, int &key, int &length) {
int * TempArray = new (nothrow) int[length++];
int DestPost = 0, SourPost = 0;
cout << "The length is " << length <<endl;
while (SourPost < (length - 1))
{
cout << "SourPost " << SourPost << endl;
if (DestPost != position)
{
TempArray[DestPost] = list[SourPost];
SourPost ++;
}
else TempArray[DestPost] = key;
cout << "DestPost " << DestPost << endl;
DestPost++;
}
if (position == (length - 1))
TempArray[DestPost] = key;
delete [] list;
list = TempArray;
cout << key << " has been inserted.\n";
}
Exactly, doesnt look like wrong to me, and the thing is, althought I got the error about the heap corruption, it actually produces the correct result if I ignore the error. Do you think it is something to do with the indexing of those two arrays?? Do you have a better approach to insert a number to a dynamic array please?
what I mean is, first i define my ArrayOfNumber in the main, then I call the insert funciton so to insert an element into my exisitng ArrayOfNumber, and it works absolutely fine.
However, if I call the insert function again to insert another element, then it gives me error of heap corruption, but the strange thing is I can really just ignore it and I sitll have the correct output.
If you've overwritten memory, the applications behaviour is non-deterministic. It actually depends on what you've overwritten and it's impact and is dependent on implementation and runtime environment.
One implementation of a heap is to maintain a linked list of allocated blocks. If the next pointer follows the end of the block, and you write off the end of the block, you'll overrite the block's next pointer, which can cause unpredicable heap behavour later on.
This is a classic problem in C/C++ and there have been various attempts to detect this problem over the decades. Visual C++ places guard bytes around each block in a debug build, so an overrite can be detected. ValGrind does a similar thing with a custom allocator.