C/C++ 採用值傳遞機制。函數參數 char *p 在調用時被拷貝一份副本 _p,_p 與實參 p 指向同一地址。若在函數內對 _p 進行 malloc,只是修改了副本指向的地址,原實參 p 仍指向 NULL,且產生內存洩漏。
void GetMemory(char *p, int n) {
p = (char*)malloc(n); // 只修改了副本 _p
}
void Test() {
char *str = NULL;
GetMemory(str, 100); // str 仍為 NULL
strcpy(str, "hello"); // 崩潰
}
void GetMemory2(char **p, int n) {
*p = (char*)malloc(n); // 解引用修改實參指向的地址
}
void Test2() {
char *str = NULL;
GetMemory2(&str, 100); // 傳遞地址
strcpy(str, "hello");
puts(str);
free(str);
}
適用:C 風格 API、需兼容 C 編譯器、輸出參數語義明確。
char *GetMemory3(int n) {
return (char*)malloc(n); // 直接返回新地址
}
void Test3() {
char *str = GetMemory3(100);
strcpy(str, "hello");
puts(str);
free(str);
}
優勢:調用語法自然(str = GetMemory3(...)),無雙重指針認知負擔,符合現代 C/C++ 風格。
void GetMemory4(char *&p, int n) { // 參考傳遞,無副本
p = new char[n];
}
void Test4() {
char *str = nullptr;
GetMemory4(str, 100);
// ...
delete[] str;
}
char *GetString() {
char p[] = "hello world"; // 棧上數組,函數返回即銷毀
return p; // 警告:返回局部變量地址
}
調用者拿到的是懸空指針,解引用導致未定義行為(輸出亂碼或崩潰)。
// 靜態存儲區:生命周期 = 程序全期,但不可修改、非線程安全
const char *GetConstString() { return "hello world"; }
// 堆內存:調用者負責 free/delete
char *GetHeapString() { return strdup("hello world"); } // POSIX
| 成因 | 代碼示例 | 防範措施 |
|---|---|---|
| 未初始化 | int *p; *p = 1; | 定義即初始化:int *p = nullptr; 或 int *p = malloc(...) |
| free/delete 後未置空 | free(p); ... if (p) *p = 0; | free(p); p = nullptr; 形成肌肉記憶 |
| 超出作用域 | { int a; p = &a; } *p = 1; | 嚴格限制指針生命周期 ≤ 指向對象生命周期,必要時用 shared_ptr |
#include
#include
std::unique_ptr GetBuffer(size_t n) {
return std::make_unique(n); // 自動 delete[]
}
void ModernTest() {
auto buf = GetBuffer(100);
strcpy(buf.get(), "hello");
// 無需手動 free,離開作用域自動釋放
}
unique_ptr:獨占所有權,零開銷,delete[] 自動匹配數組。shared_ptr:共享所有權,控制塊開銷約 16 字節,支持線程安全引用計數。string/vector:字符串與動態數組首選容器,完全避免裸指針操作。unique_ptr/string/vector 實現 RAII。