c++ - 避免堆损坏

标签 c++ pointers memory operating-system heap-memory

今天,在 EFNet C++ Wiki 上的文章 heap corruption ,我找到了两段代码。

void this_is_bad() /* You wouldn't believe how often this kind of code can be found */    
{    
    char *p = new char[5];    /* spend some cycles in the memory manager */    
    /* do some stuff with p */    
    delete[] p;      /* spend some more cycles, and create an opportunity for a leak */    
 }  

替代方法:

void this_is_good()    
{    
   /* Avoid allocation of small temporary objects on the heap*/   
   char p[5];    /* Use the stack instead */   
   /* do some stuff */  
}    

谁能帮我理解为什么第一段代码被认为不好?

最佳答案

当使用 char* p 时,您是在堆上分配 p,所以您必须注意在最后删除它。在 char *pdelete 之间,在 do some stuff with p 中,代码可能会抛出异常和 p 泄露了。

当使用 char p[5] 时,您在堆栈上分配 p,这样您就不必处理 delete,即使代码抛出异常,你也是安全的。

void this_is_bad()   
{    
  char *p = new char[5]; //on the heap
  // What happens if I throw an unhandled exception here?
  delete[] p;  // I never get to delete p and it gets leaked
}  

关于c++ - 避免堆损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11036751/

相关文章:

c++ - BST 关于 C++ 错误

c++ - 将 Javascript 函数作为参数传递给 C++ 函数

c - 将 X 索引的内存复制到 C 中单个数组中的多个位置的最佳方法是什么?

C Free Memory 使用 free

c++ - 如何获取亮像素或暗像素的坐标?打开简历

c++ - 类型引用的无效初始化

c - 在方法内部初始化 char 指针

linux - oom-killer 杀死 Docker 中的 java 应用程序 - 报告内存使用不匹配

caching - mongodb:强制内存中

c++ - 确定 TMenuItem 中文本的高度,以决定通过 TMenuItem.OnMeasureItem 更改 MenuItem 的高度