2013-06-12 87 views
0

我是C的新手,我的程序中有内存泄漏。为什么内存泄漏在这个代码中?

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; 
} 

在其他地方,我把这个过程:

while(MT_reduce(&MT)==1); 

分配给MTnewMT地址之前我释放旧资源,但为什么会出现内存泄漏?如何在不泄漏内存的情况下用newMT替换MT

回答

5

为了避免内存泄漏,你应该修改以下列方式代码:

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; 
} 

你应该总是免费newMT,即使你不复制它。

+0

不错!它解决了我的问题,谢谢! –