heap corruption detected after normal block(#174)

avi karbol picture avi karbol · Mar 1, 2013 · Viewed 9.1k times · Source

i know this question has been asked bat i couldn't fix me program

  void swap1(char*str1,char*str2)
{
    char *ezer =new char[strlen(str1)];
    for (int i = 0 ; i <= strlen(str1);i++)
        ezer[i]=str1[i];
    delete [] str1;
    str1= new char[strlen(str2)];
    for (int i = 0 ; i <= strlen(str2);i++)
        str1[i]=str2[i];
    delete [] str2;
    str2= new char[strlen(ezer)];
    for (int i = 0 ; i <= strlen(ezer);i++)
        str2[i]=ezer[i];
    delete[] ezer;
}

one time the first time it's work bat in 2nd (with other value) time i get an error the error came in the last line delete[] ezer; why i cant delete ezer?

the error:

heap corruption detected after normal block (#174) at 0x007D7A48
CRT detected that the application wrote to memory end of heap buffer

Answer

Ron Dahlgren picture Ron Dahlgren · Mar 1, 2013

strlen doesn't count the null terminator at the end of your strings. This means that after one application of your swap function, the two strings will be swapped, but will no longer be null terminated. The behavior of strlen on a string without a null terminator is undefined, meaning that you are running outside the bounds of allocated heap when you traverse one of these butchered strings.

Strings in C are represented as a character pointer with a zero-valued byte indicating the end of the string (the null terminator I mentioned). Any library routine that operates on "strings" expects to be provided a character array with the end marked by null, and will have undefined behavior otherwise (since you would be providing a char array, not a string at that point).

Use the library function strcpy instead of rolling your own.

See this question for details.