今天,在 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 *p
和 delete
之间,在 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/