5

I have:

int *ptr = new int[8];
delete[] ptr;  //  it ok, all ptr is delete;

but if I have:

int *ptr = new int[8];
ptr++; 
delete[] ptr;

My question:

Does delete[] delete all ptr from ptr[0] to ptr[7] or just from ptr[1] to ptr[7]? And, if it deletes from ptr[1] to ptr[7], how does delete[] know the real size to delete this time?

1
  • 2
    You can't release just a part of an allocation - all or nothing are your only options. Commented Nov 20, 2015 at 12:13

1 Answer 1

18

Neither; it's undefined behaviour, which usually means it'll crash the program.

The pointer you pass to delete[] must be one that was previously returned from new[]. No exceptions*. new[] returned a pointer to the first element of the array, so you must pass a pointer to the first element of the array to delete[].

* the only exception is that you can pass a NULL pointer, in which case it will do nothing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.