【问题标题】:Memory is not deallocated while creating array of pointers to pointers in c++ [closed]在c ++中创建指向指针的指针数组时不会释放内存[关闭]
【发布时间】:2014-05-15 08:16:08
【问题描述】:

我有一个创建二维数组并释放它的基本函数。但是当我使用泄漏检测器测试我的程序时,它会给出泄漏输出。

template <class T1>
T1** 
CreateMatrix(int row ,int col) 
{
  int i;
  T1** matrix;
  matrix = (T1**) malloc(row*sizeof(T1*));
  for (i=0; i<row; i++)
        matrix[i]=(T1*) malloc(col*sizeof(T1));
  return matrix;
}


template <class T1>
void FreeMatrix(int row,T1** matrix) 
{
   int i;
   for (i=0; i<row; i++)
      free(matrix[i]);
   free(matrix);    
}

int** my_matrix=CreateMatrix<int>(3,2);

FreeMatrix<int>(3,my_matrix);

【问题讨论】:

  • 你为什么使用 malloc 而不是 new? stackoverflow.com/questions/184537/…
  • 盯着你的代码看了一会儿,我觉得你的检漏仪有问题。
  • 更好的是,使用像std::vector这样的类。
  • 如果您还发布了您从“泄漏检测器”(即内存分析器)收到的消息,将会很有帮助。
  • 在 valgrind 下运行您的代码后,我几乎可以肯定您的检漏仪误报了泄漏。

标签: c++ memory memory-management memory-leaks


【解决方案1】:

提供的代码(在撰写此答案时)似乎不足以准确说明您遇到泄漏的原因,或者您是否确实遇到了泄漏。

如果您对此感兴趣,请发布一个完整但最小的示例,供读者编译和试用。

要解决问题,无论它是什么(假设它确实存在),只需使用std::vector 进行存储即可。它会自动处理内存管理。例如,即开即用,

template< class Item >
class Matrix
{
private:
    std::vector<Item>  items_;
    int                width_;

    auto index_of( int x, int y ) const
        -> int
    { return y*width_ + x; }

public:
    auto operator()( int x, int y )
        -> Item&
    { return items_[index_of( x, y )]; }

    auto operator()( int x, int y ) const
        -> Item const&
    { return items_[index_of( x, y )]; }

    Matrix( int w, int h )
        : items_( w*h )
        , width_( w )
    {}
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 2022-01-18
    • 2016-08-21
    • 2013-12-30
    相关资源
    最近更新 更多