Link to home
Start Free TrialLog in
Avatar of spiffles
spiffles

asked on

Heap Corruption with delete

Why does the following result in heap corruption
char* tempString = new char(strLen+1)
for( i = 0; i < strLen; i++)
{
    *(tempString+1) = 'A';
}
tempString[srcLen] = NULL;    
delete tempString                      // Heap Corruption with delete []tempString


If i replace the allocation line with
char* tempString = new char [strLen + 1];
it works? why?
Avatar of praveen_mundlapati
praveen_mundlapati
Flag of Australia image

You have to match the allocation with deallocation

malloc/free
new/delete
new []/ delete []

Avatar of spiffles
spiffles

ASKER

Well thats the thing; isn't new and delete matching? If I match the allocation/deallocation routines with a new and delete; heap corruption still occurs

Note if I comment out the code in between the new and delete call it works; I'm just curious as to what happens internally as a result of the code in between? How does that code result in the delete complaining about heap corruption?
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks that was what I was looking for (got mixed up with malloc where you specify the size). Yes it should be in c++ :)