【发布时间】:2012-06-17 16:50:38
【问题描述】:
今天,在 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 */
}
谁能帮我理解为什么第一段代码不被认为是好的?
【问题讨论】:
-
在第一个 sn-p 中编写 cmets 的人让我觉得不专业。很好的一点是,5 字节的分配在堆栈上通常比在堆上更有意义,并且异常安全性也很好,但是可以通过较少轻率的评论来更好地说明这一点(以“你不会相信”是一个不好的迹象)。
-
顺便说一下,搜索 cmets 看起来不是维基百科而是这个站点:efnetcpp.org/wiki/Heap_Corruption
-
我的错,其实我很着急。我读了维基。
标签: c++ pointers memory operating-system heap-memory