devjeetroy
devjeetroy

Reputation: 1945

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;

Upvotes: 2

Views: 27351

Answers (2)

arnkore
arnkore

Reputation: 435

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

Upvotes: 4

Blastfurnace
Blastfurnace

Reputation: 18652

You function can be simplified to:

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

    std::copy_n(editBuffer, editBufferSize, temp);

    delete[] editBuffer;

    editBufferSize *= 2;  

    editBuffer = temp;
}

Upvotes: 3

Related Questions