Reputation: 51
What I'm asking is if a pointer should be deleted even if nullptr has been assigned to it.
For example, in the following case:
std::string* foo = new std::string ("foo");
foo = nullptr;
Is the memory occupied before nullptr released or are we facing a memory leak?
Upvotes: 1
Views: 2107
Reputation: 10733
You have use delete for each new in your code. This is definitely a memory leak.
EDITED AS PER COMMENTS:- If you are using smart pointers then definitely you should not care about memory management details.
Upvotes: 0
Reputation: 613302
No, this code leaks the object that you allocated with new
.
If an object is allocated with new
, it must be deallocated with delete
.
What I'm asking is if a pointer should be deleted even if nullptr has been assigned to it.
The terminology that you use indicates that you are thinking about this the wrong way. It's not the pointer that you need to delete, rather the object. The pointer is just a way for your code to refer to the object. The pointer variable contains the address of the object. You can have multiple pointer variables that all refer to the same object. You do not delete the pointer, you delete the object.
Now, it might seem odd that you write the deallocation like this:
delete foo;
Naively you might think of that as meaning, delete the pointer foo. But it does not mean that. It means, delete the object whose address is stored in foo.
Upvotes: 12
Reputation: 10001
This is a memory leak. However, it is not unreasonable to want that the object gets automatically deleted. This is supported by the standard library:
std::unique_ptr<std::string> foo = new std::string ("foo");
//better:
auto foo = std::make_unique<std::string>("foo");
//also see std::shared_ptr and std::make_shared
foo = nullptr; //automatically deletes the string
It is considered bad style to have new
or delete
in code since it is unnecessarily difficult to manage memory manually.
Upvotes: 3
Reputation: 7128
Any memory allocated through new must be deallocated through delete, otherwise there will be memory leak. If you allocated as:
std::string *p = new std::string();
deallocate as:
delete p;
If you allocated as:
std::string *p = new std::string[10]; // more than one
deallocate as:
delete [] p;
Upvotes: 0