【问题标题】:free memory for matrix in NTL (Number Theory Library)NTL(数论库)中矩阵的可用内存
【发布时间】:2021-07-15 23:25:29
【问题描述】:

大家! 我在 SGX 飞地内使用 NTL。当我运行应用程序时,我遇到了关于out of memory 的问题。然后我检查了内存,我猜是由于大量使用了NTL矩阵。

NTL中矩阵的基本使用:

Mat<size_t> mtemp;
mtemp.SetDims(num_row, num_col);

NTL matrix.cpp,我没有找到任何释放内存的函数。

对于kill(),实现大概是swap()

template<class T>
void Mat<T>::kill()  
{  
   Mat<T> tmp;
   this->swap(tmp);
}  

void swap(Mat& other)
   {
      _mat__rep.swap(other._mat__rep);
      _ntl_swap(_mat__numcols, other._mat__numcols);
   }

template<class T>
void _ntl_swap(T*& a, T*& b)
{
   T* t = a; a = b; b = t;
}

这无助于释放矩阵的内存。使用后如何释放内存?

【问题讨论】:

    标签: c++ memory-leaks out-of-memory ntl


    【解决方案1】:

    kill() 函数应该做到这一点。
    假设实现Mat::~Mat()是为了释放内存。

    template<class T>
    void Mat<T>::kill()  
    {  
       // This allocates an object with absolute minimum size (probably zero).
       Mat<T> tmp;
    
    
       // Now you swap the zero size matrix with your current matrix
       // memory. 
       this->swap(tmp);
    
       // So your object `this` now holds a zero size matrix.
       // While the object `tmp` holds what used to be in this object.
       // So all the dynamically allocated memory is now inside `tmp`
    }
    // At this point `tmp` goes out of scope.
    // This causes the destructor of `tmp` to be called which
    // deallocates the memory that you used to have.
    //
    // So at this point your object holds a mtrix of zero size.
    // and all the old memory has been deallocated.
    

    【讨论】:

    • 这实际上解释了我想知道的。我再次用kill测试了NTL矩阵,内存不足的问题似乎不是由NTL矩阵引起的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多