Kodewick
開始學 →
malloc 和 free20 / 30

C 語言malloc 和 free

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

malloc(n * sizeof(int)) 在堆上申請記憶體,返回它的位址,失敗時返回 NULL;用完要 free,calloc 申請的記憶體會清零。

上一課在堆上要過記憶體。這一課把 malloc 和 free 講清楚:要多少位元組、要不到怎麼辦、拿到的記憶體裡有什麼、什麼時候還。先看一個完整的例子:在堆上放 5 天的氣溫。

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *temps = malloc(5 * sizeof(int));6    if (temps == NULL) {7        printf("記憶體不夠\n");8        return 1;9    }10    for (int i = 0; i < 5; i++) {11        temps[i] = 20 + i;12    }13    printf("第一天 %d 度,最後一天 %d 度\n", temps[0], temps[4]);14    free(temps);15    temps = NULL;16    return 0;17}
輸出
第一天 20 度,最後一天 24 度

用堆上的記憶體,總是這四步:

步驟這裡的寫法
要:算好位元組數,呼叫 mallocmalloc(5 * sizeof(int))
查:看看是不是 NULLif (temps == NULL)
用:像陣列一樣用下標temps[i] = 20 + i;
還:用完 freefree(temps);

點單步:走過第 5 行,堆裡出現一個「20 位元組」的塊,從 temps 畫過去一根箭頭;迴圈每轉一圈,塊裡多一個數;走過 free,塊變成灰色,標著「已釋放」。最後一行把 temps 設成 NULL,箭頭也沒了,下一課講為什麼要這樣做。

要多少位元組

malloc 只認位元組數,不知道你要放什麼。要放 n 個某種型別的值,就寫 n * sizeof(型別)。sizeof(int) 在這裡是 4,sizeof(double) 是 8:

double *prices① = malloc②(count * sizeof(double)③);
  1. ①堆疊上的指標,存著塊的位址
  2. ②到堆上要一塊記憶體
  3. ③位元組數:3 × 8 = 24
malloc 只認位元組數:個數乘上每個的大小
main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int count = 3;6    double *prices = malloc(count * sizeof(double));7    prices[0] = 4.5;8    prices[1] = 12.0;9    prices[2] = 3.25;10    double total = 0;11    for (int i = 0; i < count; i++) {12        total += prices[i];13    }14    printf("%zu 位元組,合計 %.2f\n", count * sizeof(double), total);15    free(prices);16    return 0;17}
輸出
24 位元組,合計 19.75

(為了短,這裡的幾個例子沒寫檢查 NULL;自己的程式裡要寫。)

只寫個數、忘了乘 sizeof,是很常見的錯:malloc(3) 只要了 3 個位元組,連一個 int 都放不下。

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

發生了什麼: 停在第 6 行:越過了 malloc 來的這一塊(3 個位元組)的末尾(越界了)。

真的 C 不會提醒你,多寫的位元組會蓋到別的東西上,程式可能過一會兒才出怪事。我們的引擎在第 6 行就停下了:這一塊只有 3 個位元組,放一個 4 位元組的 int 已經越界。點「看看是怎麼出錯的」,看堆上那個「3 位元組」的塊。

小技巧: 也可以寫 malloc(3 * sizeof *steps):*steps 是一個 int,sizeof *steps 就是 4。以後把 int 改成 double,這一行不用跟著改。

單選猜錯也沒關係

單步走過第 5 行,堆上的塊標著多少位元組?

1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    double *weights = malloc(4 * sizeof(double));6    for (int i = 0; i < 4; i++) {7        weights[i] = 60.5 + i;8    }9    printf("%.1f\n", weights[3]);10    free(weights);11    return 0;12}
練習 1

修好它

這段程式要了記憶體,可是一用就越界。改好 malloc 那一行,讓它顯示 9.5 7.0 8.5。

要顯示
9.5 7.0 8.5
exercise1.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    double *ratings = malloc(3);6    if (ratings == NULL) {7        return 1;8    }9    ratings[0] = 9.5;10    ratings[1] = 7.0;11    ratings[2] = 8.5;12    printf("%.1f %.1f %.1f\n", ratings[0], ratings[1], ratings[2]);13    free(ratings);14    return 0;15}
輸出
點「執行」或按 Ctrl+Enter

檢查 NULL

記憶體不是無限的。malloc 要不到那麼多時,返回 NULL。拿到以後先檢查,再用:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    char *big = malloc(100000000000);6    if (big == NULL) {7        printf("要不到 100 GB\n");8        return 1;9    }10    big[0] = 'A';11    free(big);12    return 0;13}
輸出
要不到 100 GB

一次要 100 GB,一般的電腦給不了,malloc 返回了 NULL,程式顯示一句話就結束了。不檢查的話,big[0] = 'A'; 就是往 NULL 裡寫,程式會崩潰。return 1; 告訴系統:程式沒有順利結束。

malloc 返回的型別是 void *,意思是「一個位址,不說裡面放什麼」。在 C 裡,它可以直接存進 int *、double *、char * 這些指標,不用寫別的。

單選

一次要的記憶體太多,malloc 給不了。會怎樣?

練習 2

平均分

在堆上要 4 個 int,檢查是不是 NULL,放進 78、85、90、77,顯示 平均分:82.50,最後 free。

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

拿到的記憶體裡有什麼

malloc 只管找一塊地方,不管裡面是什麼。塊裡原來是什麼就還是什麼,和沒賦值的變數一樣(第 2 課):

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

發生了什麼: 停在第 7 行:這塊記憶體還沒有賦值就被用了。真 C 裡這會是一個亂數(每次執行都可能不一樣)。

counts[1] 還沒賦過值。真的 C 會顯示一個說不準的數,每次執行都可能不一樣;我們的引擎在第 7 行停下來告訴你。

單選猜錯也沒關係

這段程式會怎樣?

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

calloc:要來就是 0

要一塊全是 0 的記憶體,用 calloc。它要兩個引數:幾個、每個多少位元組。它會把整塊清成 0:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int votes[8] = {2, 0, 1, 2, 2, 0, 1, 2};6    int *counts = calloc(3, sizeof(int));7    for (int i = 0; i < 8; i++) {8        counts[votes[i]]++;9    }10    for (int i = 0; i < 3; i++) {11        printf("%d 號:%d 票\n", i, counts[i]);12    }13    free(counts);14    return 0;15}
輸出
0 號:2 票
1 號:2 票
2 號:4 票

計數要從 0 開始,calloc 正合適。點單步,走過第 6 行,堆上的塊是「12 位元組」,三格都是 0;之後每投一票,就有一格加 1。

堆疊

aint *
bint *

堆

? ? ?malloc(12)
0 0 0calloc(3, 4)
malloc 給的塊裡是什麼說不準(?),calloc 給的塊全是 0
猜輸出猜錯也沒關係

這段程式顯示什麼?

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

數骰子

rolls 裡是 10 次擲骰子的結果(1 到 6)。用 calloc 要 7 個 int 當計數器(下標 1 到 6 用來計數),數完顯示每個點數出現了幾次,格式是 1:2,每個一行,最後 free。

要顯示
1:2
2:1
3:2
4:1
5:1
6:3
exercise3.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int rolls[10] = {3, 6, 1, 3, 5, 6, 6, 2, 1, 4};6 7    return 0;8}
輸出
點「執行」或按 Ctrl+Enter

用完就 free

free(p) 把 p 指著的塊還回去,以後這塊記憶體可能分給別人用。幾條規矩:

  • 每個 malloc 或 calloc 來的塊,最後都要 free 一次,只能一次;
  • free 的必須是 malloc 或 calloc 給你的那個位址,不能是普通變數的位址;
  • free 以後,塊裡的東西不能再碰;
  • free(NULL) 什麼也不做,是安全的。
main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *a = malloc(2 * sizeof(int));6    int *b = malloc(4 * sizeof(int));7    a[0] = 1;8    b[0] = 2;9    printf("%d %d\n", a[0], b[0]);10    free(a);11    free(b);12    return 0;13}
輸出
1 2

點單步:堆上先後出現兩個塊,一個「8 位元組 · 第 5 行」,一個「16 位元組 · 第 6 行」。走過第 10 行,第一個塊變灰;走過第 11 行,第二個也變灰。程式結束時,堆上沒有還沒還的塊。違反這幾條規矩會怎樣,下一課一個一個看。

單選

寫了 int n = 3;、int *a = malloc(sizeof(int));、int *b = &n; 以後,哪一句 free 是錯的?

這一課學會了

  • malloc(n * sizeof(型別)) 在堆上要 n 個值的地方,返回塊的位址;malloc 只認位元組數。
  • 要不到時 malloc 返回 NULL:拿到先檢查,再用。
  • malloc 給的記憶體沒有清零,先賦值再用;要全是 0,用 calloc(個數, 每個的位元組數)。
  • 用完 free:每塊一次,只能 free malloc / calloc 給的位址,free(NULL) 什麼也不做。
  • 單步時堆上每個塊都標著位元組數和是哪一行要來的;free 以後它變灰,標著「已釋放」。
第 20 課學完了嗎?第 20 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 21 課 · 15 分鐘記憶體洩漏和懸空指標學 C 語言用堆最常見的幾種錯:忘了 free 的記憶體洩漏、丟了指標、free 以後接著用、free 兩次、free 不是 malloc 來的位址,以及 free 後設成 NULL。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。