編譯通過,運行彈出異常對話框(截圖顯示訪問違例/段錯誤),功能看似正常但實際已 Crash。
**指針相關錯誤概率最高**:
void* 強轉不匹配類型)。0xC0000005 = 訪問違例(空指針/越界/野指針)。0xC00000FD = 棧溢出。gflags /p /enable YourApp.exe /full,重現 Crash 獲取詳細堆棧。| 模式 | 風險點 | 修正 |
|---|---|---|
char *p; strcpy(p, "abc"); | 野指針 | char *p = malloc(4); 或 char p[100]; |
int *p = (int*)malloc(4); free(p); *p = 1; | use-after-free | 釋放後置 NULL,或用智能指針 |
void foo(int *p) { *p = 1; } int main() { foo(NULL); } | 空指針解引用 | 入口參數檢查 if (!p) return; |
sprintf(buf, "%s", longStr); | 緩衝區溢出 | 用 snprintf/std::string |
std::unique_ptr/std::vector/std::string 替代裸指針/手動 malloc/free。int *p = nullptr; 或 int *p = new int(0);。at() 或斷言。/analyze 或用 Coverity/Clang-Tidy 掃描。「編譯通過 ≠ 正確」,**調試器是定位 Crash 的唯一可靠工具**,養成 F5 調試習慣,查看調用堆棧直達故障行。