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 undefined
Last Comment

8/22/2022 - Mon

You have to match the allocation with deallocation

new []/ delete []



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?
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question

thanks that was what I was looking for (got mixed up with malloc where you specify the size). Yes it should be in c++ :)