本地練習/ 用 ./run.sh 開 sanitizer 跑:未定義行為在這裡「剛好沒崩」會教歪。
宣告 int *p = &x; 後,*p 與 x 是同一格;透過 *p 寫值就是改 x。預測 printf("%d %d", x, *p)。
// 透過指標改值 int x = 10; int *p = &x; // p 指向 x *p = 20; // 改的是 x 本人 printf("%d %d\n", x, *p);
C 是傳值,函式拿到複本。要改呼叫端的變數,把位址傳進去,函式內用 * 寫回。看記憶體圖追 a、b 指向誰。
void swap(int *a, int *b){ int t = *a; *a = *b; *b = t; } // 呼叫: int x = 3, y = 5; swap(&x, &y); // x=5, y=3
a[i] 等同 *(a+i);p+n 以 sizeof(*p) 為單位移動。改下面的 i 預測 *(p+i)。
大小到執行期才知道、或要活過函式,就向 heap 要:malloc → 檢查 NULL → 用 → free → 設 NULL。看記憶體圖:指標在 stack、資料在 heap、free 後那塊歸還。
malloc(stack-only)。動態配置的完整可跑版在 本地練習/03_dynamic_array.c:./run.sh 03_dynamic_array.c這些在瀏覽器「剛好沒崩」會給錯誤的安全感。到 本地練習/ 用 ./run.sh 檔名.c(已開 -fsanitize=address,undefined),錯誤才穩定現形。
free 後再解參考。./run.sh 05_use_after_free.c → heap-use-after-freefree 兩次。./run.sh 06_double_free.c → double-freefree。mac 上 sanitizer 抓不到,需 Instruments;見 README