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

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

4

1 回答 1

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。

于 2013-06-12T17:53:41.350 回答