Is the following C++ code a memory leak?
list.push_back(new String("hi"));
As I understand it, push_back from any std collection/container always makes a copy. So if the new string is copied, nothing can ever delete the new'd string right? since there is no reference to it after the push_back...
Am I correct or wrong here?
Thanks.
Jbu
edit: I think I am wrong, since new will return a pointer...we'll always have the pointer to be able to delete the new String
If I saw this code I would be very suspicious a memory leak was possible. On the surface it appears to be adding an allocated
String*
into alist<String*>
. In my experience this is often followed by bad error handling code which does not properly free the allocated memory.While this dangerous in many circumstances it is not necessarily a memory leak. Consider the following example:
In this code there is no leak because the containing class is responsible for the memory allocated and will free it in the destructor.
EDIT
As aschepler pointed out there is still a leak if the
push_back
method throws an exception.Why are you allocating dynamic strings in the first place? Unless you want to communicate between different parts of your program by changing strings (which would be quite unusual), get rid of the pointer:
No, the vector stores pointers and the copy is made of the pointer. You can delete the object any time later.
(You may get a leak, if the statement happens to throw an exception and you don't catch and handle it properly. That's why you might consider using smart pointers.)
Yes, but not for the reason you think.
Depending on how
list
is defined and initialized,push_back
might throw an exception. If it does, the pointer returned fromnew
is lost, and can never be freed.But assuming
push_back
returns successfully, it stores a copy of the pointer returned bynew
, and so we can free the memory later by callingdelete
on that copy, so no memory is leaked as long as you do calldelete
properly.You are correct, provided nothing deletes the string when it is removed from the list.
No.
You can delete the object by doing:
or clear the whole list by: