Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you deallocate a pointer twice or more in C++?

int main() {     Employee *e = new Employee();      delete e;     delete e;     ...     delete e;     return 0; } 
like image 403
flopex Avatar asked Apr 30 '10 18:04

flopex


People also ask

What happens if we delete a 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.

What happens if you free a pointer twice in C?

If we free the same pointer two or more time, then the behavior is undefined. So, if we free the same pointer which is freed already, the program will stop its execution.

Is it safe to delete the same pointer twice?

No! (Assuming you didn't get that pointer back from new in between.)

What happens when you delete a pointer in C?

The pointer itself does have an address and the value. The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).


1 Answers

You get undefined behaviour if you try to delete an object through a pointer more than once.

This means that pretty much anything can happen from 'appearing to work' to 'crashing' or something completely random.

like image 89
CB Bailey Avatar answered Sep 21 '22 12:09

CB Bailey