Kodewick
開始學 →
記憶體洩漏和懸空指標21 / 30

C 語言記憶體洩漏和懸空指標

第 21 課,共 30 課 · 第 4 部分 · 記憶體 · 約 15 分鐘

記憶體洩漏是 malloc 的記憶體忘了 free;懸空指標是 free 之後還在用的指標。free 之後把指標設成 NULL 能避免後者。

堆上的記憶體自己要、自己還。這一課看「還」出了錯會怎樣:忘了還、還了還在用、還了兩次。先看忘了還:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int *make_week(int base) {5    int *steps = malloc(7 * sizeof(int));6    for (int i = 0; i < 7; i++) {7        steps[i] = base + i * 100;8    }9    return steps;10}11 12int main(void) {13    for (int week = 1; week <= 3; week++) {14        int *steps = make_week(week * 1000);15        printf("第 %d 周第一天:%d 步\n", week, steps[0]);16    }17    return 0;18}
輸出
第 1 周第一天:1000 步
第 2 周第一天:2000 步
第 3 周第一天:3000 步

輸出看不出任何問題,程式也正常結束了。點單步走到最後:堆上有三個「28 位元組 · 第 5 行」的塊,迴圈每轉一圈多一個,一個也沒還。程式結束時它們還在,每個都標著紅色的「記憶體洩漏」。

忘了 free

這一課開頭的程式裡,make_week 每呼叫一次就在堆上要 28 個位元組,main 用完卻從來不還。要了記憶體卻沒有還,叫記憶體洩漏。每一圈,main 裡的 steps 都指著一個新塊,舊的那個就再也沒有指標指著了:沒人能用它,也沒人能還它。

指標就像鑰匙:鑰匙丟了,塊還佔著地方,可誰也打不開它、也還不回去

這個程式跑一下就結束了,結束時系統會把它的記憶體都收回去,所以看不出害處。可是一個一直開著的程式(伺服器、瀏覽器、遊戲)要是每處理一次就漏一點,它佔的記憶體就越來越多,最後慢得不行,甚至被系統關掉。

真的 C 程式漏了記憶體,什麼也不會說,輸出和沒漏一模一樣。我們這裡執行時也不會提醒;要看出來,就點單步走到最後,看堆上還剩著哪些塊。

單選

程式漏了記憶體。點執行,輸出會怎樣?

丟了指標

不光是忘了寫 free。把指標改去指別的地方,原來的塊也就找不回來了:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *prices = malloc(3 * sizeof(int));6    prices[0] = 12;7    prices = malloc(5 * sizeof(int));8    prices[0] = 30;9    printf("%d\n", prices[0]);10    free(prices);11    return 0;12}
輸出
30

點單步:走過第 7 行,prices 的箭頭從「12 位元組」的塊轉到了新的「20 位元組」的塊上,舊塊那裡一根箭頭也沒有了。第 10 行的 free 還的是新塊。走到最後,舊塊標著「記憶體洩漏」。

堆疊

pricesint *NULL

堆

12 ? ?int[3]
30 ? ? ? ?int[5]

prices 改指新塊的那一刻,舊塊就找不回來了
單選

int *p = malloc(4 * sizeof(int)); 之後又寫了 p = malloc(8 * sizeof(int));,第一塊就漏了。怎麼改?

修好洩漏

規矩很簡單:每個要來的塊,在最後一個指著它的指標丟掉之前,還回去。這一課開頭的例子裡,用完這一週就 free:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int *make_week(int base) {5    int *steps = malloc(7 * sizeof(int));6    for (int i = 0; i < 7; i++) {7        steps[i] = base + i * 100;8    }9    return steps;10}11 12int main(void) {13    for (int week = 1; week <= 3; week++) {14        int *steps = make_week(week * 1000);15        printf("第 %d 周第一天:%d 步\n", week, steps[0]);16        free(steps);17    }18    return 0;19}
輸出
第 1 周第一天:1000 步
第 2 周第一天:2000 步
第 3 周第一天:3000 步

再點單步走到最後:三個塊都是灰色的「已釋放」,沒有紅色的了。

小技巧: 寫下一個 malloc 的時候,馬上想好:誰來 free 它,在哪一行。函式返回一塊堆記憶體時,寫一句註解,說清楚呼叫它的人要負責 free。

單選

一個函式 malloc 了一塊記憶體,再把位址 return 給呼叫它的地方。誰來 free?

還了還在用

還有一種錯更危險:塊已經還了,指標還指著那裡,接著用。這樣的指標叫懸空指標。

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *balance = malloc(sizeof(int));6    *balance = 500;7    free(balance);8    printf("餘額:%d\n", *balance);9    return 0;10}
輸出
heap-use-after-free

發生了什麼: 停在第 8 行:這塊記憶體已經 free 了(還回去了),不能再用。

free 以後,balance 裡的位址沒有變,可那塊記憶體已經不是你的了,系統隨時可能把它分給別人。真的 C 程式可能照樣顯示 500,可能顯示一個亂數,也可能過了很久才在別的地方出事。我們的引擎在第 8 行停下來。點「看看是怎麼出錯的」:塊已經變灰,balance 的箭頭變成了紅色虛線。

常見的情況是兩個指標指著同一塊,用一個還了,另一個還在用:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *scores = malloc(3 * sizeof(int));6    scores[0] = 88;7    int *best = scores;8    free(scores);9    printf("最高分:%d\n", best[0]);10    return 0;11}
輸出
heap-use-after-free

發生了什麼: 停在第 9 行:這塊記憶體已經 free 了(還回去了),不能再用。

best = scores 複製的只是位址,兩根箭頭指著同一個塊。還了一次,兩個指標就都懸空了。

堆疊

scoresint *
bestint *NULL

堆

88 ? ?int[3]

兩個指標指著同一塊:用一個還了,兩個都懸空
單選猜錯也沒關係

這段程式會怎樣?

1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *p = malloc(sizeof(int));6    *p = 7;7    int v = *p;8    free(p);9    printf("%d\n", v);10    return 0;11}
練習 1

還早了

這段程式 free 得太早,後面還在用。挪一挪那一行,讓它顯示 第一名:95 和 第二名:88,並且程式結束前把記憶體還掉。

要顯示
第一名:95
第二名:88
exercise1.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *top = malloc(2 * sizeof(int));6    top[0] = 95;7    top[1] = 88;8    printf("第一名:%d\n", top[0]);9    free(top);10    printf("第二名:%d\n", top[1]);11    return 0;12}
輸出
點「執行」或按 Ctrl+Enter

free 兩次

同一塊還兩次也不行。比如兩個指標指著同一塊,各 free 一次:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *list = malloc(4 * sizeof(int));6    int *copy = list;7    list[0] = 7;8    copy[1] = 9;9    free(list);10    free(copy);11    return 0;12}
輸出
attempting double-free

發生了什麼: 停在第 10 行:這塊記憶體已經 free 過了,不能再 free 一次。

copy 和 list 是同一個塊,第 9 行已經還了,第 10 行又還一次。真的 C 程式常常在這裡崩潰,有時還會把堆弄亂、讓後面的 malloc 出錯。我們的引擎在第 10 行停下。

單選猜錯也沒關係

這段程式會怎樣?

1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *a = malloc(sizeof(int));6    int *b = malloc(sizeof(int));7    free(a);8    free(b);9    printf("OK\n");10    return 0;11}
練習 2

只還一次

orders 和 today 指著同一塊記憶體,程式把它還了兩次。刪掉多餘的那一句,讓程式顯示 今天 39 單,並且正常結束。

要顯示
今天 39 單
exercise2.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *orders = malloc(3 * sizeof(int));6    orders[0] = 12;7    orders[1] = 7;8    orders[2] = 20;9    int *today = orders;10    printf("今天 %d 單\n", today[0] + today[1] + today[2]);11    free(orders);12    free(today);13    return 0;14}
輸出
點「執行」或按 Ctrl+Enter

只還 malloc 來的

free 只能還 malloc(或者 calloc、realloc)給你的位址。普通變數在堆疊上,函式結束自己就沒了,不歸你還。free 這樣的位址也是錯:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int count = 3;6    int *p = &count;7    *p = 4;8    free(p);9    return 0;10}
輸出
main.c: In function 'main':
main.c:8:5: warning: 'free' called on unallocated object 'count' [-Wfree-nonheap-object]
    8 |     free(p);
      |     ^~~~~~~
main.c:5:9: note: declared here
    5 |     int count = 3;
      |         ^~~~~
attempting free on address which was not malloc()-ed

發生了什麼: 停在第 8 行:「count」不是 malloc 來的,不能 free。free 只能用在 malloc / calloc / realloc 給的指標上。

這次 gcc 編譯時就看出來了,給了警告;可警告不會攔住程式。我們的引擎在第 8 行停下:count 不是 malloc 來的。

單選猜錯也沒關係

這段程式會怎樣?

1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int n = 5;6    int *p = malloc(sizeof(int));7    int *q = &n;8    *p = n;9    free(p);10    free(q);11    return 0;12}

free 以後設成 NULL

一個好習慣:free 以後,馬上把指標設成 NULL。這樣它就不再懸空,用之前查一下 != NULL 就知道它還能不能用;不小心再 free 一次也沒事,因為 free(NULL) 什麼也不做。

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *cart = malloc(2 * sizeof(int));6    cart[0] = 15;7    cart[1] = 40;8    printf("合計:%d\n", cart[0] + cart[1]);9    free(cart);10    cart = NULL;11    if (cart != NULL) {12        printf("購物車還在\n");13    } else {14        printf("購物車已經清空\n");15    }16    free(cart);17    return 0;18}
輸出
合計:55
購物車已經清空

點單步:走過第 10 行,cart 的箭頭沒了,變成 NULL。

單選猜錯也沒關係

這段程式會怎樣?

1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *a = malloc(sizeof(int));6    int *b = a;7    free(a);8    a = NULL;9    free(b);10    return 0;11}
練習 3

安全地還

寫好函式 release:free 引數 p,然後返回 NULL。main 寫的是 data = release(data);,所以呼叫兩次也不會出錯。程式要顯示 data 是 NULL。

要顯示
data 是 NULL
exercise3.c
1#include <stdio.h>2#include <stdlib.h>3 4int *release(int *p) {5 6}7 8int main(void) {9    int *data = malloc(4 * sizeof(int));10    data = release(data);11    data = release(data);12    if (data == NULL) {13        printf("data 是 NULL\n");14    }15    return 0;16}
輸出
點「執行」或按 Ctrl+Enter

這一課學會了

  • 要了不還,叫記憶體洩漏:輸出看不出來,程式越跑佔的記憶體越多。單步走到最後,沒還的塊標著「記憶體洩漏」。
  • 把指向一個塊的最後一個指標改掉或丟掉之前,先 free 它。
  • free 以後接著用(懸空指標)、同一塊 free 兩次、free 不是 malloc 來的位址,都是未定義行為,我們的引擎會停下說明。
  • 兩個指標指著同一塊時,free 一次,兩個都懸空了;只能還一次。
  • free 以後把指標設成 NULL:用之前查得出來,再 free 也沒事;但別的指著同一塊的指標不會跟著變。
第 21 課學完了嗎?第 21 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 22 課 · 15 分鐘會長大的陣列學 C 語言用 realloc 做一個會長大的陣列:realloc 怎麼用、為什麼先存進另一個指標、長度和容量、為什麼容量要翻倍,以及把它寫成函式。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。