内存未被完全破坏-内存泄漏
Memory not destroyed completely - memory leak
我在代码中使用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是查找泄漏的工具;使用它。
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏