Kodewick
開始學 →
堆疊和堆19 / 30

C 語言堆疊和堆

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

區域性變數放在堆疊上,函式返回時自動釋放;用 malloc 申請的記憶體放在堆上,一直存在,直到你 free 它。

程式跑起來以後,變數放在記憶體裡。C 程式的記憶體裡有兩塊地方你要分清:堆疊和堆。到現在為止,我們寫的變數都在堆疊上。點單步,記憶體畫面分成「堆疊」和「堆」兩塊:

main.c
1#include <stdio.h>2 3int add(int a, int b) {4    int sum = a + b;5    return sum;6}7 8int main(void) {9    int price = 30;10    int total = add(price, 12);11    printf("合計:%d\n", total);12    return 0;13}
輸出
合計:42

一開始堆疊上只有 main 的框,裡面是 price 和 total。呼叫 add 時,上面多了一個框,放著 a、b、sum;add 一返回,這個框就沒了。堆那一塊一直是空的。

堆疊堆
放什麼函式的引數和區域性變數用 malloc 要來的記憶體
誰來管自動:呼叫時有,返回時沒你自己:自己要,自己還
活多久到函式結束到你 free 它
堆疊上一個函式一個框:呼叫時放上去,返回時拿走。堆上的塊不歸哪個函式管,靠指標找到它

堆疊:函式結束就沒了

每呼叫一次函式,堆疊上就多一個框(第 8 課叫它堆疊幀),函式返回,框就拿掉。所以區域性變數只活到函式結束。第 18 課見過一個指向區域性變數的指標,函式一返回就懸空了。陣列也一樣:想讓函式做好一個數組交出來,直接返回區域性陣列,是行不通的:

main.c
1#include <stdio.h>2 3int *make_scores(void) {4    int scores[3] = {78, 85, 90};5    return scores;6}7 8int main(void) {9    int *p = make_scores();10    printf("%d\n", p[0]);11    return 0;12}
輸出
main.c: In function 'make_scores':
main.c:5:12: warning: function returns address of local variable [-Wreturn-local-addr]
    5 |     return scores;
      |            ^~~~~~
load of null pointer

發生了什麼: 停在第 10 行:這個指標是 NULL(空指標),不能通過它讀寫。

gcc 先給了一個警告:函式返回了局部變數的位址。它還是編譯了,而且因為這個位址拿出去也沒法用,gcc 乾脆讓 make_scores 返回 NULL。所以第 10 行通過 p 去讀時,我們的引擎停下了:p 是 NULL。點「看看是怎麼出錯的」,一步一步看:make_scores 的框一拿掉,框裡的陣列也跟著沒了。

main()

pint *NULL

make_scores()

scoresint[3]78 85 90

區域性陣列住在 make_scores 的框裡:框一拿掉,陣列也跟著沒了
單選

函式返回以後,它的區域性變數怎樣?

堆:自己要,自己還

想要一塊不會跟著函式消失的記憶體,就到堆上去要。malloc 在 <stdlib.h> 裡,你告訴它要多少位元組,它在堆上找出這麼大的一塊,把位址交給你;用完了,用 free 把它還回去:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *p = malloc(sizeof(int));6    *p = 42;7    printf("堆上的數:%d\n", *p);8    free(p);9    return 0;10}
輸出
堆上的數:42

點單步,走過第 5 行:堆裡出現了一個塊,標著「4 位元組 · 第 5 行」,也就是它有多大、是哪一行要來的。p 自己在堆疊上,是 main 框裡的一個指標,一根箭頭從它指向堆上的塊。走過第 8 行的 free,塊變成灰色,標著「已釋放」:這塊記憶體還回去了,不能再用。malloc 的細節(要多少位元組、要不到怎麼辦)下一課再講。

單選猜錯也沒關係

變數 price 本身放在哪裡?

1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    double *price = malloc(sizeof(double));6    *price = 9.5;7    printf("%.1f\n", *price);8    free(price);9    return 0;10}
填空點一個填進空格,再點空格可以拿回來

選一個填進空格:在堆上要一個 int,放進 42,用完還回去。程式顯示 42。

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

堆上的價格

用 malloc 在堆上要一個 double,把 19.5 放進去,顯示 價格:19.50,最後 free 它。

要顯示
價格:19.50
exercise1.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5 6    return 0;7}
輸出
點「執行」或按 Ctrl+Enter

活得比函式久

堆上的塊不歸哪個函式管,函式返回了,它還在。所以要讓函式做出一組數交給呼叫它的地方,就在堆上做:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int *make_scores(void) {5    int *scores = malloc(3 * sizeof(int));6    scores[0] = 78;7    scores[1] = 85;8    scores[2] = 90;9    return scores;10}11 12int main(void) {13    int *p = make_scores();14    printf("%d %d %d\n", p[0], p[1], p[2]);15    free(p);16    return 0;17}
輸出
78 85 90

區域性陣列在函式返回時就跟著沒了。這裡只改了一處:陣列換成了堆上的塊。點單步看:make_scores 返回時,它的框沒了,框裡的 scores 指標也沒了,可堆上那個「12 位元組」的塊還在,main 裡的 p 接著指著它。塊是 make_scores 要來的,最後由 main 還回去:誰還都行,只要還一次。

main()

pint *NULL

make_scores()

scoresint *NULL

堆

78 85 90int[3]

scores 在 make_scores 的框裡,它指著的塊在堆上:框沒了,塊還在
單選

make_scores 返回以後,它的區域性變數 scores 和 scores 指著的堆上的塊怎樣?

練習 2

修好它

make_prices 返回了一個區域性陣列的位址,程式一用就出事。改成在堆上要記憶體,讓程式顯示 12 8 25,並在 main 裡用完後 free。

要顯示
12 8 25
exercise2.c
1#include <stdio.h>2#include <stdlib.h>3 4int *make_prices(void) {5    int prices[3] = {12, 8, 25};6    return prices;7}8 9int main(void) {10    int *p = make_prices();11    printf("%d %d %d\n", p[0], p[1], p[2]);12    return 0;13}
輸出
點「執行」或按 Ctrl+Enter

大小要等跑起來才知道

這門課裡的陣列,大小都是寫程式碼時就定下的常量,比如 int a[7]。可很多時候,要放多少個數得等程式跑起來才知道:比如從一組成績裡挑出及格的,挑完才知道有幾個。這時就按算出來的個數到堆上去要:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int scores[6] = {58, 72, 91, 45, 60, 83};6    int count = 0;7    for (int i = 0; i < 6; i++) {8        if (scores[i] >= 60) {9            count++;10        }11    }12    int *passed = malloc(count * sizeof(int));13    int k = 0;14    for (int i = 0; i < 6; i++) {15        if (scores[i] >= 60) {16            passed[k] = scores[i];17            k++;18        }19    }20    printf("及格 %d 人:", count);21    for (int i = 0; i < count; i++) {22        printf("%d ", passed[i]);23    }24    printf("\n");25    free(passed);26    return 0;27}
輸出
及格 4 人:72 91 60 83 

count 是 4,所以堆上的塊是 4 × 4 = 16 位元組,不多不少。

小技巧: C 也允許 int a[n] 這種大小是變數的陣列(叫變長陣列),但它放在堆疊上,n 太大就會出事,C11 起編譯器也可以不支援它。這個頁面不支援它。要的個數是變數時,用 malloc。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int a[5] = {4, 9, 2, 7, 5};6    int count = 0;7    for (int i = 0; i < 5; i++) {8        if (a[i] > 4) {9            count++;10        }11    }12    int *big = malloc(count * sizeof(int));13    printf("%zu\n", count * sizeof(int));14    free(big);15    return 0;16}
練習 3

平方表

寫好函式 make_squares:在堆上要 n 個 int,第 i 個放 (i + 1) * (i + 1),返回這塊記憶體的位址。程式要顯示 1 4 9 16 25 ,然後換行。

要顯示
1 4 9 16 25 
exercise3.c
1#include <stdio.h>2#include <stdlib.h>3 4int *make_squares(int n) {5 6}7 8int main(void) {9    int *squares = make_squares(5);10    for (int i = 0; i < 5; i++) {11        printf("%d ", squares[i]);12    }13    printf("\n");14    free(squares);15    return 0;16}
輸出
點「執行」或按 Ctrl+Enter

堆疊不大,堆大

堆疊的空間不大,在常見的電腦上一般只有幾 MB,一個函數裡要是宣告一個幾百萬個元素的陣列,就可能把堆疊撐爆,程式直接崩潰。堆可以大得多,能用到電腦的大部分記憶體。所以很大的陣列也放到堆上:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int count = 1000000;6    int *steps = malloc(count * sizeof(int));7    for (int i = 0; i < count; i++) {8        steps[i] = 5000;9    }10    printf("一共 %d 天,第一天 %d 步\n", count, steps[0]);11    free(steps);12    return 0;13}
輸出
一共 1000000 天,第一天 5000 步

一百萬個 int 是 4000000 位元組,差不多 4 MB,放在堆疊上很危險,放在堆上沒問題。(這段程式迴圈一百萬圈,別點單步一圈一圈地看,點執行就好。)

什麼時候用堆,記住三種情況:

  • 要的個數等程式跑起來才知道;
  • 這塊記憶體要比要它的函式活得久;
  • 東西很大,堆疊上放不下。

除此以外,用普通的區域性變數就好:不用自己還,也就不會忘了還。

多選可以選多個

哪些情況該用堆?(可以選好幾個)

這一課學會了

  • 函式的引數和區域性變數在堆疊上:呼叫時多一個框,返回時框就沒了,裡面的變數也沒了。
  • 不要返回區域性變數的位址:函式一返回,那裡就不是你的了。
  • 堆上的記憶體用 malloc 要、用 free 還;函式返回了,它還在。
  • 指標本身可以在堆疊上,它指著的塊在堆上。
  • 三種情況用堆:個數要跑起來才知道、要活得比函式久、東西太大堆疊上放不下。
第 19 課學完了嗎?第 19 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 20 課 · 15 分鐘malloc 和 free學 C 語言 malloc 和 free:用 sizeof 算要多少位元組、檢查返回的是不是 NULL、malloc 給的記憶體沒清零、用 calloc 清零、用完 free。單步看堆上的塊出現和釋放。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。