Search code examples
c++dynamic-memory-allocation

Dynamic memory allocation for character arrays


Okay, so I was trying to resize an array as follows :

if((editBufferCounter + 20) > editBufferSize)
{
    char* temp;
    temp = new char[editBufferSize + 5];

    strcpy(temp, editBuffer);

    delete[] editBuffer;

    editBufferSize *= 2;  

    editBuffer = new char[editBufferSize];

    strcpy(editBuffer, temp);

    delete[] temp;

}

The last line delete[] temp causes a memory problem. The program simply crashes. I can't seem to get what the problem here is.

Note: The program runs fine if i remove the line delete[] temp;


Solution

  • Do your editBuffer have a terminating NUL character? if not, please replace strcpy with strncpy.