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
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.
Double-deletion is when you delete an email message from your inbox and then immediately delete it from the trash folder as well.
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.
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.
Deleting the same memory twice is undefined behaviour. Anything may happen, including nothing. It may e.g. cause a crash sometime later.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With