2013-06-12 85 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

不錯!它解決了我的問題,謝謝! –