C++ delete pointer twice

17,968

Solution 1

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

Solution 2

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.

Solution 3

I tried doing this in Visual Studio. There are two cases:

1)

delete p;
delete p;

This compiles properly but gives debug assertion failure when you run the program because you are trying to delete the memory location which is already deleted and no longer belongs to you.

2)

delete p;
p = NULL;
delete p;

This compiles properly and runs properly. There is no error. Try printing p before and after delete.

Share:
17,968
Person.Junkie
Author by

Person.Junkie

Updated on June 07, 2022

Comments

  • Person.Junkie
    Person.Junkie almost 2 years

    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
    
  • DevSolar
    DevSolar over 9 years
    ...and because that's the point where certain people go cavalier ("hell, works for me, can't be that bad"), I usually add "...or it may format your hard drive". ;-)
  • user1198065
    user1198065 over 9 years
    Any ideas on how to debug if the program is crashing sometime later on? I faced this scenario and had to undo all my change before I found that I was deleting it twice. Would like to know if there is a better way to go about it.
  • cjsimon
    cjsimon about 6 years
    Why is it undefined behavior? Does it just attempt to delete whatever's in the designated memory location?
  • user904963
    user904963 about 2 years
    @cjsimon Undefined behavior is usually about speed. Defining what happens would imply runtime checks that take CPU cycles to complete. A compiler is free to handle the situation any way it likes or not handle it at all (often the case, especially with optimization levels selected). It will most likely blindly update as if a valid object was there or crash fast as the code that keeps track of these things might assume delete is only ever called on pointers that came from new.