Nelson T Joseph
Nelson T Joseph

Reputation: 2763

Delete a character array in VC++

I have the following code. When I try to delete the pDest, error occurs. How can I delete pDest. Is there any other operation need to delete this?

{
    int nReqLen = nSrcLength;
    char* pDest = new char[nReqLen+1];
        .
        .
        .
        .
    memcpy( (char*)pSource, pDest, nSrcLength );
    delete pDest;
    return nReturn;
}

Upvotes: 0

Views: 144

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361772

delete pDest;

It invokes undefined behavior, because pDest is allocated memory using new T[N] form.

If you use new T[] syntax, then you've to write delete []t syntax.

If T is typdef of U[N] and you write new T, even then you've to use delete []t. For example,

typedef int IntArr[100];

int *pint = new IntArr; //See it is not of the form of new T[N];

//delete pint; //wrong
delete [] pint; //correct

Upvotes: 0

AndersK
AndersK

Reputation: 36092

You need to use [] in the delete

delete [] pDest; since it is an array

Upvotes: 0

rob mayoff
rob mayoff

Reputation: 386018

You need to say delete[] pDest. It was allocated as an array so it needs to be deleted as an array.

Upvotes: 4

Related Questions