避免堆损坏

Gre*_*lin 4 c++ memory heap operating-system pointers

今天,在文章堆损坏的 EFNet C++ Wiki上,我找到了两段代码.

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 */    
 }  
Run Code Online (Sandbox Code Playgroud)

替代方式:

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

有人可以帮助我理解为什么第一段代码不被认为是好的吗?

Rya*_*yan 7

在使用时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
}  
Run Code Online (Sandbox Code Playgroud)

  • 评论也试图传达"新"和"删除"不是免费的操作.而在堆栈上分配数组通常意味着从堆栈指针寄存器中减去非常快速的数据. (2认同)