在C ++中为数组正确分配和释放内存 [英] Correct allocate and free memory for arrays in C++

查看:88
本文介绍了在C ++中为数组正确分配和释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理动态数组.函数empty_matrix()创建一个新的数组,表示一个矩阵. delete_matrix()释放分配给矩阵的所有内存.

I'm dealing with dynamic arrays. The function empty_matrix() creates a new array, representing a matrix. delete_matrix() frees all memory, allocated for the matrix.

如果我调用add(add(a, b), c),是否在函数example()中出现内存泄漏?在函数add(...)中分配的内存将如何处理?我必须释放它吗?我应该在哪里做?

Do I get a memory leak in function example() if I call add(add(a, b), c)? What will happen to the memory allocated in the function add(...)? Do I have to free it? Where should I do it?

 matrix empty_matrix(int dim) {
 matrix m;
 m.dim = dim;
 m.data = new int*[dim];
 for (int i = 0; i < dim; i++)
  m.data[i] = new int[dim];

 return m;
}

void delete_matrix(matrix m) {
 for (int i = 0; i < dim; i++)
  delete [] m.data[i];
 delete [] m.data;
}

matrix add(matrix a, matrix b) {
 matrix c = empty_matrix(a.dim);
 for (int i = 0; i < a.dim; i++)
  for (int j = 0; j < a.dim; j++)
   c.data[i][j] = a.data[i][j] + b.data[i][j];

 return c;
}

void example() {
 matrix a = empty_matrix(100);
 matrix b = empty_matrix(100);
 matrix c = empty_matrix(100);

 // some modifications of a, b and c
 // ...

 matrix d = add(add(a, b), c);
 print_matrix(d);

 delete_matrix(a);
 delete_matrix(b);
 delete_matrix(c);
 delete_matrix(d);
} 

推荐答案

应该要做的是使用对象方向/RAII.您的矩阵类的数据成员应为私有的,并且为其分配的内存应在构造函数中分配,并在析构函数中释放.这样,您就不必担心内存泄漏.

What you should do is use Object Orientation/RAII. Your data member of matrix class should be private, and memory for it should be allocated in the constructor, and freed in the destructor. This way, you won't have to worry about memory leaks.

例如...

class matrix
{
public:
      typedef int element_type;
      matrix(int dimension)
          :data_(new element_type[dimension*dimension])
      {

      }  
      //Do define your copy-constructor and assignment operators
      ~matrix()
      {
         delete [] data_;
      } 

private:
      element_type* data_;
};

如果这是家庭作业,那么所有这些当然就可以了.如果不是,那么在这种情况下,应避免使用数组.使用std::vector s

This all, of course, if this is homework. If it is not, then you should refrain from using arrays in this situation. Use std::vectors

这篇关于在C ++中为数组正确分配和释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆