如何 fix/correctly initialise/clean 向上矩阵 class 泄漏内存

How to fix/correctly initialise/clean up matrix class leaking memory

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

#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;};

我觉得这很好。是吗?内存真的泄漏了吗?如何解决?我可能声明或初始化不正确吗?

你们都在使用初始化列表和显式初始化。

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);
}

应该修复内存泄漏