在 C++ 中動態配置記憶體時,選擇正確的位址分配方式至關重要。本文對比兩種常見寫法,揭示為何使用 new 獨立配置符合設計預期,而指標遞增(p++)會導致邏輯錯誤。
#include <iostream>
using namespace std;
void main() {
int *p = new int;
cin >> *p;
while (*p != 0) {
cout << p; // 輸出位址呈連續分佈(如陣列)
p++; // 指標遞增,指向下一個 int 位置
cin >> *p;
}
cout << *p << endl;
}
問題分析:
p++ 使指標按 sizeof(int) 位元組遞增,產生連續記憶體區塊,類似陣列。#include <iostream>
using namespace std;
void main() {
int *p = new int;
int *q;
cin >> *p;
while (*p != 0) {
cout << p; // 輸出位址為隨機分佈,符合預期
q = new int; // 每次獨立配置新記憶體
p = q; // p 指向新區塊
cin >> *p;
}
cout << *p << endl;
}
優勢:
new int 向作業系統請求獨立記憶體區塊,位址隨機分佈。delete 釋放記憶體(本範例為簡化省略)。| 操作 | 記憶體分佈 | 適用場景 | 風險 |
|---|---|---|---|
p++ / p + i | 連續(陣列式) | 已知大小的連續資料結構(陣列、向量) | 若未配置足夠空間,存取越界導致 UB |
每次 new 配置 | 離散(隨機) | 動態數量、獨立生命週期的物件 | 需手動管理釋放,否則記憶體洩漏 |
最佳實踐:現代 C++ 建議使用智慧指標(std::unique_ptr、std::shared_ptr)或容器(std::vector)自動管理記憶體,避免手動 new/delete 帶來的風險。