[英]Memory not destroyed completely - memory leak
我在代码中使用2D数组,并且希望在使用fun
之前和使用fun
,应用程序具有相同的已使用内存量。 但是不幸的是,这些价值观并不相同。 当我在fun
开始时检查用过的内存时(从代码中开始-使用/proc/self/statm
,其中OS是linux),这是一定数量的,而当我在return ...
之前检查用过的内存return ...
在fun
函数中,不是和以前一样。 您能看到一些内存泄漏吗? 我认为所有内存在不必要的时候都会被破坏,但是也许有些问题: 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等)并不是判断程序正在泄漏的最佳方法,它可以告诉您程序大小在增加,但这不一定是由于泄漏引起的。 例如,分配模式可能导致堆中的碎片,这有可能迫使分配器增大堆,以获取足够大的连续范围以包含请求的分配。 我并不是说您的示例就是这种情况,但这只是不使用statm得出内存问题的许多原因之一。
简而言之,valgrind是查找泄漏的工具。 用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.