Search code examples
c++stringstlc-stringsheap-corruption

Heap corruption when deleting a string


Here is my code:

std::string readString()
{
     int strLen = Read<int>();
     char* rawString = new char[strLen];
     Read(rawString, strLen);
     rawString[strLen] = '\0';
     std::string retVal(rawString);
     delete [] rawString;
     return retVal;
 }

The first line reads the length of the string.
The second line creates a new char array (c-string) with the string length
The third line reads the string (its reading it from a file)
The 4th line adds a NULL to the end.
The 5th line creates an std::string out of the c-string.
The 6th line deletes the c-string (HEAP CORRUPTION HAPPENS HERE)
The 7th line returns the string, but it never reaches this point because of an error.

On the 6th line I get a heap corruption error: CRT detected that the application wrote to memory after end of heap buffer.

My question may be obvious, but why am I getting a heap corruption? When I create an std::string, it should copy the string, and I should be safe to delete the c-string.

Currently, I'm suspecting that std::string is trying to access the c-string after I delete it.

Any ideas?


Solution

  • Change:

    char* rawString = new char[strLen];
    

    to:

    char* rawString = new char[strLen + 1];