内存未被完全破坏-内存泄漏

Memory not destroyed completely - memory leak

本文关键字:内存 泄漏      更新时间:2023-10-16

我在代码中使用2D数组,我想在使用fun之前和使用它之后,由应用程序使用相同数量的内存。但不幸的是,这些价值观并不相同。当我检查fun开始时使用的内存(从代码-使用/proc/self/statm,其中操作系统是linux),它是一些数量,当我检查fun函数中return ...之前使用的内存时,它与以前的数量不一样。您能看到一些内存泄漏吗?我认为所有的记忆在不必要的时候都在破坏,但也许有什么问题:actualVertices = newVertices;。你觉得呢?

编辑:第一次检查——在创建Independentsets之后,第二次检查在返回之前,所以Independentsets不是问题。除此之外,在Main中删除了Independentsets。acrualvertices和newVertices在内存中存在问题

编辑2:也许像这样检查内存:

double getUsedMemory()
{
    int tSize = 0, resident = 0, share = 0;
    ifstream buffer("/proc/self/statm");
    buffer >> tSize >> resident >> share;
    buffer.close();
    return  (double)(resident - share) / ToMBfromB * sysconf(_SC_PAGE_SIZE);
}

有问题吗?你知道更好的方法来编程内存统计吗?

int** CreateVertices(int row, int col) // Creating 2D array
{
    int** nVertices = new int*[row];
    for (int i = 0; i < row; ++i)
        nVertices[i] = new int[col]();
    return nVertices;
}
void DeleteVertices(int** tab, int rowCount) // Detroying 2D array
{
    for (int i = 0; i < rowCount; ++i)
        delete[] tab[i];
    delete[] tab;
}
int* fun(..., int n)
{
    int* independentSets;
    int** actualVertices;
    int** newVertices;
    int actualVerticesRowCount = n;
    int actualVerticesColCount = 1;
    independentSets = new int[1 << n] ();
    // first memory checking 
    actualVertices = CreateVertices(n, 1);
    for (int i = 0; i < n; ++i)
    {
        independentSets[1 << i] = 1;
        actualVertices[i][0] = i;
    }
    for (int el = 1; el < n; el++)
    {
        int col = el + 1;
        int row = Combination_n_of_k(n, col);
        newVertices = CreateVertices(row, col);
        int l = 0;
        for (int i = 0; i < actualVerticesRowCount; ++i)
        {
            // some computations...
            for (int j = actualVertices[i][actualVerticesColCount - 1] + 1; j < n; ++j)
            {   
                // some computations...
                for (int k = 0; k < el; ++k)
                    newVertices[l][k] = actualVertices[i][k];
                newVertices[l][el] = j;
                l++;
            }
        }
        DeleteVertices(actualVertices, actualVerticesRowCount);
        if (el != n - 1)
            actualVertices = newVertices;
        actualVerticesRowCount = row;
        actualVerticesColCount = col;
    }
    DeleteVertices(newVertices, actualVerticesRowCount);
    // second memory checking 
    return independentSets;
}

我会使用valgrind并对任何您怀疑有内存泄漏的东西运行它。使用statm(或top等)并不是告诉您程序正在泄漏的最佳方法——它可以告诉您程序大小正在增加,但这并不一定是由于泄漏造成的。例如,分配模式可能会导致堆中的碎片,这可能会迫使分配器增加堆,以获得足够大的连续跨度来包含请求的分配。我并不是说您的示例中就是这种情况,但这只是不使用stat来断定存在内存问题的众多原因之一。

简单地说,valgrind是查找泄漏的工具;使用它。