Reputation: 111
Does using a new then setting to null cause memory leaks?
Ive tried the following code but have no idea if it causes any leak or not
#include <iostream>
using namespace std;
int main()
{
int* x = new int;
int y = 1;
x = &y;
x = nullptr; // has the memory allocated to x gone now?
x =&y; // did i recover what was lost?
delete x;
return 0;
}
// the cout<<*x gives 1 as expected
Upvotes: 0
Views: 112
Reputation: 34618
The pointed-to-object is lost when you assign to the only pointer that holds it. As stated above, x = &y
already loses your new int
. Nothing you do afterwards can bring it back. This means that the delete
invokes undefined behaviour and might crash your program.
However, there is a mechanism in C++ that avoids such memory leaks: Smart Pointers.
In C++ smart pointers come in two main varieties ::std::unique_ptr<T>
and ::std::shared_ptr<T>
. They have the job of holding on to an object in dynamic memory and make sure to delete it when it becomes unowned:
::std::unique_ptr<int> x = ::std::make_unique<int>(0);
x = nullptr; // automatically deletes the previously allocated int
This is slightly more expensive than raw pointers but it is less prone to memory leaks. Smart pointers live in the <memory> header.
Upvotes: 1
Reputation: 753
Yes, this is a leak. However, the leak does not occur when you assigned nullptr
to x
, but rather in the line before it:
x = &y;
x
now points to the address of y
, and no other references to the memory you allocated with new int
exist. Without any references to that memory, there's no way to deallocate it.
Upvotes: 4