Reputation: 3
C++ Memory Leak using list class and push_back
void EMAdd(int n)
{
list<Employee*> em;
for (int i = 1; i <= n; i++)
em.push_back(new Employee());
}
Q1. at the end , the destructor of class list automatically deletes the nodes of em?
Q2. But why this function still has a memory leak?
Thanks, I would appreciate your answer!
Upvotes: 0
Views: 2362
Reputation: 96835
You should have a list
of unique_ptr
s so that the memory will be freed upon destruction:
std::list<std::unique_ptr<Employee>> em;
But as David Brown said, you shouldn't be using pointers to begin with.
Upvotes: 2
Reputation: 13526
The destructor of Employee
is not called. You have a list
of pointers to Employee
objects, not a list of Employee
objects. When the list's destructor is called it will destroy the pointers to the Employee
object, but not the objects they point to which you created with new Employee()
. They will still be in memory but the only references to them are lost when the list is destroyed, leaking that memory.
Remember every call to new
must have a matching call to delete
somewhere. However, better yet don't use pointers at all and simply use a list of Employee
objects directly.
void EMAdd(int n)
{
list<Employee> em;
for (int i = 1; i <= n; i++)
em.push_back(Employee());
}
Since each element in std::list
is already dynamically allocated, a list of pointers is redundant and essentially gives you a set of pointers to pointers.
Upvotes: 6