What happens when you deallocate a pointer twice or more in C++?
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.
C++ delete pointer twice
Deleting the same memory twice is undefined behaviour. Anything may happen, including nothing. It may e.g. cause a crash sometime later.
deallocation of same pointer twice not giving error if I make the pointer NULL
You need to deallocate only what you allocate. You allocate five instances of MyClass
with new[]
. So that's what you need to deallocate.
You're not deallocating any pointers. Pointers don't need to be deallocated unless you dynamically allocated them, and your code doesn't dynamically allocate any pointers.
When you make the pointer nullptr
(or NULL
), it doesn't point to anything. So calling delete
on it has no effect. The C++ standard chose to make calling delete
(or delete[]
) on a null pointer do nothing.
C++ delete pointer allocated twice
Therefore what happens to the other pointer in this case?
It is lost. You dropped the last reference to the array A
was pointing to (A
and B
are not pointing to pointers. They are pointers and they do point at the first element of the arrays, ie int
s, respectively).
And how can we delete it?
You cannot. The memory is leaked.
Don't ever use raw owning pointers. For dynamic arrays you can use std::vector
and for others you can use smart pointers. With std::vector
your code would be:
#include <vector>
int main{
auto A = std::vector<int>(4);
auto B = std::vector<int>(4);
A = B;
}
And for the sake of completeness also a leak-free version of your code:
void please_dont_do_this() {
int * A = new int[4];
int * B = new int[4];
delete [] A; // delete the array before the pointer is lost
A = B;
delete[] B; // delete the array only once !
}
PS: I know this view isnt very popular among enthusiastic beginners who want to learn as much as possible, but imho the most important thing you need to know about raw pointers in C++ is that you almost never need them (and when you think you need them then most likely you still don't).
Calling free on a pointer twice
When you use malloc
you are telling the PC that you want to reserve some memory location on the heap just for you. The computer gives back a pointer to the first byte of the addressed space.
When you use free
you are actually telling the computer that you don't need that space anymore, so it marks that space as available for other data.
The pointer still points to that memory address. At this point that same space in the heap can be returned by another malloc
call. When you invoke free
a second time, you are not freeing the previous data, but the new data, and this may not be good for your program ;)
Why deleteing a pointer twice will cause crash?
It's hard to predict exactly what will happen -- it depends a little on the compiler, and a lot on the standard library. Officially, it's just undefined behavior, so nearly anything can happen.
The most common thing that'll happen is that the heap will get trashed. It may not check that what delete is valid, so when it gets two blocks at the same address it may (for example) still treat them as two separate blocks, so when you allocate memory later you may get that same block of memory twice. In some other cases, it may (for example) just complement a bit to say whether that block of memory is in use, so the second time you delete it, you actually end up marking it as being in use again, so that memory can never be allocated again, and you've basically just created a leak.
Why do I have to call delete twice when I have each two pointers at same memory?
When I did
delete k
, however, thek
andd
point the memory yet.
Invoking operator delete
on some pointer will ask the operating system to release the memory associated with this pointer, but doesn't change the value of the pointer itself. k
and d
simply continue pointing to that same location in memory, which is released in the mean time.
That's why sometimes people set a pointer to nullptr
after delete
-ing it. In your case, this would have saved you from undefined behavior:
delete d;
d = nullptr;
k = nullptr; // Both must be re-assigned
delete k; // Ok, delete on a nullptr is a no-op
Is it safe to delete a nullptr twice in C++?
Is it safe to delete a nullptr twice in C++?
Yes (in all standard versions of C++). It is guarnteed to work (by work, I mean it doesn't do anyting).
Deletion has no effects if the argument is a null pointer. The compiler that the presenter describes did not conform to the C++ standard. The described compiler also was from the 80's, so it was made before C++ was standardised. The presenter is wrong in saying that you can't delete the null pointer twice if they are referring to standard C++ which does seem to be implied.
It is true that deletion may indirectly cause the program to behave as if the value of the argument pointer was changed (and by as-if rule that means that they effectively can change the value), but only in case where the pointer was non-null and is thus invalidated by the deletion. In fact, this allowance applies to all pointer objects that had the same value as all of them are thereby invalidated. This is because all ways that could observe the value of an invalid pointer are either undefined or implementation defined behaviour.
What happens in a double delete?
It causes undefined behaviour. Anything can happen. In practice, a runtime crash is probably what I'd expect.
Freeing memory twice
int *p = malloc(sizeof(int));
//value of p is now lets say 0x12345678
*p = 2;
free(p); //memory pointer is freed, but still value of p is 0x12345678
//now, if you free again, you get a crash or undefined behavior.
So, after free
ing the first time, you should do p = NULL
, so if (by any chance), free(p)
is called again, nothing will happen.
Here is why freeing memory twice is undefined: Why free crashes when called twice
Related Topics
C++:Creating an Array with a Size Entered by the User
Is There a Working C++ Refactoring Tool
.C VS .Cc VS. .Cpp VS .Hpp VS .H VS .Cxx
5 Years Later, Is There Something Better Than the "Fastest Possible C++ Delegates"
Compile a Dll in C/C++, Then Call It from Another Program
Std::String Length() and Size() Member Functions
How to Std::Move Objects Out of Functions? (C++11)
How to Specify Setprecision Rounding
How to Check If the Input Is a Valid Integer Without Any Other Chars
How Do Compilers Treat Variable Length Arrays
Scope VS Life of Variable in C
Statically Declared 2-D Array C++ as Data Member of a Class
Inlining Failed in Call to Always_Inline '_M256D _Mm256_Broadcast_Sd(Const Double*)'
Waitforinputidle Doesn't Work for Starting Mspaint Programmatically
Constant Expression Initializer for Static Class Member of Type Double