一、空指針問題操作系統
try { char* p = new char[256]; strcpy(p, "hello"); int size = strlen(p); printf("strlen = %d\n", size); delete[] p; p = nullptr; strcpy(p, "world"); size = strlen(p); printf("strlen = %d\n", size); } catch (const std::exception& e) { printf("err:%s\n", e.what()); } //catch (...) //{ // DWORD errcode = GetLastError(); // printf("Unknown err, code = %d\n", errcode); //}
上面代碼中若是去掉p=nullptr那麼p就變爲了野指針,程序可能不會出錯,可是會產生巨大的隱藏風險:p指針已經被delete,所指向的內存已被操做系統回收,strcpy拷貝的數據隨時可能被後續的其餘數據所覆蓋;指針
二、除0操做產生0xc0000094異常代碼:被除數不能爲零code
try { int x = 10; int y = 0; int z = x / y; } catch (const std::exception& e) { printf("err:%s\n", e.what()); } //catch (...) //{ // DWORD errcode = GetLastError(); //// printf("Unknown err, code = %d\n", errcode); //}
三、刪除已經被刪除的對象產生未經處理的異常: 0xC0000374: 堆已損壞對象
try { A* p = new A(); p->print(); p->a = 12; p->print(); delete p; p->a = 25; p->print(); delete p; } catch (const std::exception& e) { printf("err:%s\n", e.what()); } //catch (...) //{ // DWORD errcode = GetLastError(); //// printf("Unknown err, code = %d\n", errcode); //}