malloc 無 free、fopen 無 fclose、資源句柄未關閉)。free、釋放未初始化指標、free 非 malloc 記憶體。// 1. 簡單洩漏
void f1(char *explanation) {
char *p1 = malloc(100);
sprintf(p1, "Error: %s", explanation);
log(p1); // 缺少 free(p1)
}
// 2. 資源洩漏(FILE* 無 fclose)
int getkey(char *filename) {
FILE *fp = fopen(filename, "r");
int key; fscanf(fp, "%d", &key);
return key; // 缺少 fclose(fp)
}
// 3. 未初始化指標
void f2(int datum) { int *p2; *p2 = datum; } // Segfault 風險
// 4. 重複釋放
void f3() { char *p = malloc(10), *pp = p; free(p); free(pp); } // 未定義行為
// 5. 懸空指標
int *f8() { int *xp = malloc(sizeof(int)); *xp = 13; free(xp); return xp; } // 回傳已釋放記憶體
// 6. 緩衝區溢位
void f1(char *explanation) {
char buf[100];
sprintf(buf, "Error: %s", explanation); // explanation 超過 80 字元即溢位
}
static char *important = NULL;
void f9() {
if (!important) important = malloc(BIG);
if (condition) important = malloc(SMALL); // 先前的 BIG 記憶體永久洩漏
}
-Wall -Wextra -Werror(GCC/Clang)、/W4(MSVC)。std::unique_ptr, std::shared_ptr, std::vector, std::string 自動管理生命週期。snprintf, strncpy_s, memcpy_s 等邊界檢查版本。malloc/new 必須有對應 free/delete,擁有權語義明確。盡可能避免裸指標與手動記憶體管理,採用標準容器、智慧指標、std::optional/std::variant 等高階抽象,將記憶體安全交給編譯器與執行期庫保證。