code老是無預警當掉, 用VC的debug build來run, 卻總是出現以下訊息
_ASSERT(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));而且還是dbgdel.cpp的錯誤......
google了一下, 原來double free記憶體或是buffer overflow都是這樣子的exception, VC這樣寫還真的是看不懂啊
而且, VC的release build並不會馬上對double free做出反應, 而是在不定時間crash = ="
參考以下簡單的一段code
int main(void)
{
char *n = new char[32];
delete n;
delete n;
return 1;
}
這樣的double free用VC 2005的release build來run沒有問題, gcc 4.1.1倒是會印出double free or corruption。不過, 寫作習慣比較好(這表示...偷懶的時候常常會省略)的coding方法應該要避免這種dangling pointer:
int main(void)
{
char *n = new char[32];
delete n;
n = NULL;
delete n;
n = NULL;
return 1;
}
free前先檢查是不是null pointerThe ANSI standard ANSI X3.159-1989 "Programming Language C." specifies that free(NULL) is a no op. "free deallocates the space pointed to by p: it does nothing if p is NULL." Quoted from "The C Programming Language" second edition by Kernighan and Ritchie with the subtitle "ANSI C"., free完的pointer一律設為null pointer(free完就不理它的話, 就叫做dangling pointer啦) 很麻煩的寫法, 不過卻可以保命......抓這種bug可是會要人老命的。