c++ - 如何在我的 C++ 代码中避免此类内存泄漏?

标签 c++ pointers memory-leaks

我的 C++ 代码存在内存泄漏问题。我认为这是因为指针赋值。例如,我有几行是这样的:

**int **p= new int *[g+2];          
for(int k=0;k<=g+1;k++){
    p[k]=new int [n_k[k]+1];
    for(int l=0;l<=n_k[k];l++){
        p[k][l]=0;
    }
}
int **temp= new int *[g+2];     
for(int k=0;k<=g+1;k++){
    temp[k]=new int [n_k[k]+1];
    for(int l=0;l<=n_k[k];l++){
        temp[k][l]=p[k][l];
    }
}
  ...
  ...
 for(int r=0; r<=g+1;r++){
delete []temp[r];
  }
  delete []temp;
  for(int r=0; r<=g+1;r++){
delete []p[r];
  }
   delete []p;

如何避免这些类型的内存泄漏?我删除了指针,但我认为内存泄漏是因为指针分配。我已在我的代码中多次使用此类指针赋值。

最佳答案

How can I avoid these kinds of memory leaks in my C++ code?

  • 停止使用new
  • 尽可能避免使用动态内存分配。
    如果你必须:
  • 使用标准库容器,如 std::vector
  • 使用 RAII (通过智能指针)

关于c++ - 如何在我的 C++ 代码中避免此类内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18285798/

相关文章:

c++ - 使用 fread 读入 int 缓冲区

c - C 中的重复指针资源处理

c - char 指针 (strdup) 时使用 printf 的段错误

c++ - 空指针代替 int 类型的指针

c - 内存寻址和指针

iphone - AVCaptureStillImageOutput 输出设置内存泄漏

javascript - 关闭内存泄漏并修复

c++ - 随着用户需求的增加创建对象数组?

c++ - 试图在 C++ 中对一个简单的字符串进行排序

c++ - 通过外部评估调度将标准兼容性与不透明数据连接起来