Reputation: 2799
Hi I have this following code, it take nodes from slaveQueue and preload to preload1 and preload2, But the memory is always increasing. I assume it should be released after I call dfs since all the memory should be freed after the local function returns and I checked that pop() function will also free the memory ? so I wonder where is my memory leak? THanks
queue<Graphnode> *preload1 = new queue<Graphnode>;
queue<Graphnode> *preload2 = new queue<Graphnode>;
for(int n = windowWidth; n > 0; n--)
{
if((*slaveQueue).empty())
{
//cout <<"fffffffffffff"<<endl;
break;
}
(*preload2).push((*slaveQueue).front());
//cout << (*slaveQueue).size()<<endl;
(*slaveQueue).pop();
}
int preload1No =0;
while(!(*preload2).empty())
{
preload1No++;
*slaveroot = (*preload2).front();
(*preload2).pop();
if(!(*slaveQueue).empty())
{
(*preload2).push((*slaveQueue).front());
(*slaveQueue).pop();
}
dfs(*slaveroot,goal,totalDepth,*preload1,*preload2,checkfile);
if(preload1No>windowWidth)
{
(*preload1).push(*slaveroot);
(*preload1).pop();
}
else
{
(*preload1).push(*slaveroot);
}
cout<<(*preload1).size()<<"\t"<<(*preload2).size()<<endl;
}
delete slaveroot;
delete preload1;
delete preload2;
delete slaveQueue;
Upvotes: 0
Views: 299
Reputation: 490048
When you pass a
to your function, a copy of a
itself is what gets passed. When the function exits, that copy of a
gets destroyed. The memory that a
points at isn't copied at all in your code.
Your code leaks one byte of memory1 because you're calling func1
in an infinite loop, so the delete a;
will never execute. When most people talk/think about memory leaks, however, they're thinking of "progressive" leaks -- ones that leak more memory the longer the program runs.
Upvotes: 0
Reputation: 227370
If you are not explicitly allocating any memory in func1
, and call no function that does that, then there is no memory leak. All you are copying into the function is a pointer. The copied pointer itself is on the function's stack, and gets popped along with everything else in the function's scope once the function returns.
Upvotes: 1
Reputation: 129314
Yes, it will make a copy of the pointer a
, but not of the memory that a
points to. So there is no memory leak here, and thus nothing to free.
Upvotes: 2
Reputation: 67195
It does create a copy of a
on the stack. But that memory is recovered as soon as the function returns.
If you have a memory leak, that is likely caused by code not shown here.
Upvotes: 0
Reputation: 25695
The a
in func1
is pass by value, which means its on the stack. Hence it won't create any memory leak. It is released when func
exits.
Upvotes: 1