Question

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
Was it helpful?

Solution

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.

OTHER TIPS

You are missing to allocate space for the 0-terminator here:

char *ezer = new char[strlen(str1)];

Change this to be:

char *ezer = new char[strlen(str1) + 1];

The actual (first) memory corruption happens here:

  for (int i = 0 ; i <= strlen(str1);i++)
    ezer[i]=str1[i];

As with the last iteration (the one that copies the 0-terminator) ezer[i] referrs to memory "just behind" what was allocated for ezer.

Redo the same for the other two allocations of character arrayc.

Anyhow, as this would fix the heap corruption, the function would not behave as expected. But this is another story ... isn't it? ;-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top