fin*_*g83 1 c++ heap corruption
如果我们在新数组和删除char数组之间有大量代码,为什么会出现问题.
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)
因为有人可能会抛出异常.
因为有人可能会增加回报.
如果在new和delete之间有很多代码,你可能不会发现你需要在throw/return之前释放内存吗?
为什么代码中有RAW指针.
使用std :: vector.
你引用的文章指出了这一点
char p[5];
Run Code Online (Sandbox Code Playgroud)
在这种情况下会同样有效,并且没有泄漏的危险.
通常,通过使分配的内存的生命周期非常清楚来避免泄漏,可以看到新的和删除是相关的.
两者之间的大的分离更难以检查,并且需要仔细考虑代码中是否有任何可能避免删除的方法.