今天,在 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 */
}
有人可以帮助我理解为什么第一段代码不被认为是好的吗?