[英]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.