如何修复/正确初始化/清理矩阵类泄漏内存

时间:2015-06-04 21:54:55

标签: c++ memory-leaks

以下使用SG2 package中的SmallMatrix类的示例代码似乎会导致内存泄漏。在这个简化的例子中,只有很少的内存被泄露。但是我更复杂的算法往往会耗尽内存。

#include "small_matrix.hpp"
int main() {
    SmallMatrix<double> S(1);
}

请参阅下面的Valgrind输出。

8 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C2B800: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
   by 0x400D4A: SmallMatrix<double>::SmallMatrix(int) (small_matrix.hpp:1347)
   by 0x400C15: main (test.cpp:3)

相关构造函数是源代码的引用部分:

template <class T>
SmallMatrix<T>::SmallMatrix(int the_m)
: small_matrix<T> (the_m, new T [the_m])
{
    T * alloced_entries;
    try
    {
        alloced_entries = new T [the_m];
    }
    catch(std::bad_alloc)
    {
        throw SMALL_MAT_NO_MEMORY;
    };
    small_matrix<T>::init (the_m, 1, alloced_entries);
}

Find a listing of small_matrix.hpp here.

第1347行写道:

: small_matrix<T> (the_m, new T [the_m])

析构函数可以在第822行找到:

~SmallMatrix () {delete [] SmallMatrix<T>::entry;};

这对我来说似乎很好。是吗?记忆真的泄露了吗?怎么解决?我可能会错误地宣布或初始化吗?

1 个答案:

答案 0 :(得分:5)

您正在使用初始化列表和显式初始化。

small_matrix的构造函数使用您在初始化列表中创建的数组调用init()。然后手动调用init()替换指向数组的指针。所以你放弃了对初始化列表中创建的数组的引用。

template <class T>
SmallMatrix<T>::SmallMatrix(int the_m)
: small_matrix<T> (the_m, NULL)
{
    T * alloced_entries;
    try
    {
       alloced_entries = new T [the_m];
    }
    catch(std::bad_alloc)
    {
        throw SMALL_MAT_NO_MEMORY;
    };
    small_matrix<T>::init (the_m, 1, alloced_entries);
}

应该修复内存泄漏