Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete array pointer c++ when increase pointer?

Tags:

c++

pointers

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?

like image 231
Hai Nguyen Avatar asked Nov 20 '15 12:11

Hai Nguyen


People also ask

Does delete destroy the pointer?

Yes, it destroys the object by calling its destructor. It also deallocates the memory that new allocated to store the object. Or does it only destory the pointer? It does nothing to the pointer.

What happens if you delete pointer twice?

If delete is applied to one of the pointers, then the object's memory is returned to the free store. If we subsequently delete the second pointer, then the free store may be corrupted.


1 Answers

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.

like image 133
user253751 Avatar answered Oct 01 '22 14:10

user253751