Reputation: 35
I'm a newbie in C and I have memory leak in my program.
static int MT_reduce(MT_table** MT)
{
MT_table* newMT = new_MT((*MT)->argc);
/// fill data in the newMT ////
if(isReduced == 1 && newMT->size > 0)
{
MT_free(*MT);
*MT = newMT;
}
return isReduced;
}
In other place I call this procedure:
while(MT_reduce(&MT)==1);
I'm freeing old resources before assigning to MT
the address of newMT
, but why do I get a memory leak? How I can replace MT
with newMT
without leaking memory?
Upvotes: 0
Views: 119
Reputation: 70939
In order to avoid memory leak you should edit the code in the following manner:
static int MT_reduce(MT_table** MT)
{
MT_table* newMT = new_MT((*MT)->argc);
/// fill data in the newMT ////
if(isReduced == 1 && newMT->size > 0)
{
MT_free(*MT);
*MT = newMT;
} else {
MT_free(newMT);
}
return isReduced;
}
You should always free newMT even when you do not copy it.
Upvotes: 5