Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ delete pointer twice [duplicate]

Tags:

c++

pointers

I know that a "deleting the same memory twice" error can happen when two pointers address the same dynamically allocated object. 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.

But why doesn't this code cause a run-time error?

 string *str_1 = new string;
  auto str_2 = str_1;
  *str_1 = "AAA";
  cout<<*str_2<<endl;
  delete str_1;
  delete str_2;  // No Error

    // Prints AAA
like image 525
Person.Junkie Avatar asked Aug 05 '14 11:08

Person.Junkie


People also ask

What will happen if a pointer is deleted 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 is a double delete?

Double-deletion is when you delete an email message from your inbox and then immediately delete it from the trash folder as well.

What happens if you use free 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.

What happens when you deallocate something that has been deallocated before?

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.


2 Answers

Deleting the same memory twice is undefined behaviour. Anything may happen, including nothing. It may e.g. cause a crash sometime later.

like image 157
Wojtek Surowka Avatar answered Nov 08 '22 20:11

Wojtek Surowka


I compiled this program in g++ 4.9.1 and it gave me a runtime error:

*** Error in `./t': free(): invalid pointer: 0xbfa8c9d4 ***

You are trying to free something which is already freed. Hence, the error.

like image 2
shauryachats Avatar answered Nov 08 '22 21:11

shauryachats