Kodewick
開始學 →
會長大的陣列22 / 30

C 語言會長大的陣列

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

realloc 把一塊 malloc 來的記憶體變大,常用來讓陣列隨資料增長;結果要先存進新指標,因為失敗時它返回 NULL,原來的記憶體還在。

用 malloc 要記憶體時,得說好要多少。可很多時候一開始根本不知道:一天會來幾個訂單、一個檔案裡有幾行。這一課做一個會長大的陣列:放滿了,就換一塊更大的。換塊用的是 realloc:

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

realloc(舊指標, 新的位元組數) 給你一塊新大小的記憶體,原來的內容原樣搬過去,返回新塊的位址。原來的 78 和 85 還在,後面多出了兩格可以用。

realloc 做了什麼

這一課開頭的例子裡,點單步走過第 11 行:堆上多了一個「16 位元組 · 第 11 行」的塊,裡面是 78 和 85,後兩格還空著;舊的「8 位元組」塊變成了灰色的「已釋放」。realloc 做的就是這三件事:要一塊新的、把舊的內容複製過去、把舊的還掉。

堆疊

scoresint *
biggerint *NULL

堆

78 85int[2]
78 85 ? ?int[4]

realloc 要一塊新的、把內容搬過去、把舊的還掉:舊指標 scores 這時就懸空了,直到改成新位址

在這個頁面上,realloc 每次都是這樣搬家。真的 C 裡,如果舊塊後面正好空著,它可能就地把塊變大,位址不變。你不知道它會怎麼做,所以:

  • 只用 realloc 返回的位址,別再用舊指標;
  • 舊塊已經被 realloc 還掉了,不要再 free 它,最後只 free 新的。
main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *old = malloc(2 * sizeof(int));6    old[0] = 78;7    old[1] = 85;8    int *scores = realloc(old, 4 * sizeof(int));9    printf("%d\n", old[0]);10    free(scores);11    return 0;12}
輸出
heap-use-after-free

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

第 9 行還在用 old,可它指著的塊已經被 realloc 還掉了。我們的引擎在這裡停下,和上一課「還了還在用」一樣。真的 C 裡,要是塊碰巧是就地變大的,這一行看起來沒事,換一臺電腦或者多放幾個數就出事了:這種錯最難找。點「看看是怎麼出錯的」,看 old 的紅色虛線箭頭。

單選

int *scores = realloc(old, 4 * sizeof(int)); 之後,還能用 old 嗎?

先存進另一個指標

這一課開頭的例子沒有寫 scores = realloc(scores, ...),而是先存進 bigger。原因是:要不到記憶體時,realloc 返回 NULL,而舊塊還在、沒有還。要是直接寫

1scores = realloc(scores, 4 * sizeof(int));

一失敗,scores 就變成了 NULL,舊塊再也找不到了:不但資料沒了,還洩漏了一塊記憶體。所以總是這樣寫:

1int *bigger = realloc(scores, 4 * sizeof(int));2if (bigger == NULL) {3    // scores 還能用;不要了就 free(scores)4}5scores = bigger;

小技巧: realloc(NULL, n) 和 malloc(n) 一樣。所以有人一開始把指標設成 NULL,第一次也用 realloc 來要。

單選

為什麼不直接寫 p = realloc(p, n);?

練習 1

再加兩個

scores 現在能放 3 個分數。用 realloc 把它變成能放 5 個(先存進另一個指標,檢查 NULL),放進 70 和 95,顯示 88 76 91 70 95。

要顯示
88 76 91 70 95 
exercise1.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *scores = malloc(3 * sizeof(int));6    if (scores == NULL) {7        return 1;8    }9    scores[0] = 88;10    scores[1] = 76;11    scores[2] = 91;12 13    for (int i = 0; i < 5; i++) {14        printf("%d ", scores[i]);15    }16    printf("\n");17    free(scores);18    return 0;19}
輸出
點「執行」或按 Ctrl+Enter

長度和容量

每放一個數就 realloc 一次太費事了。會長大的陣列記著兩個數:

意思變數
長度現在放了幾個count
容量這塊記憶體一共能放幾個capacity
長度是放了幾個,容量是這塊記憶體一共能放幾個:還空著兩格,下一個數可以直接放

放之前先看一眼:count 和 capacity 一樣大,說明滿了,就把容量翻一倍;沒滿就直接放。這個例子一天放一個步數,放 6 天:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int capacity = 2;6    int count = 0;7    int *steps = malloc(capacity * sizeof(int));8    if (steps == NULL) {9        return 1;10    }11    for (int day = 1; day <= 6; day++) {12        if (count == capacity) {13            int *bigger = realloc(steps, capacity * 2 * sizeof(int));14            if (bigger == NULL) {15                free(steps);16                return 1;17            }18            steps = bigger;19            capacity *= 2;20            printf("滿了,容量變成 %d\n", capacity);21        }22        steps[count] = day * 1000;23        count++;24    }25    printf("長度 %d,容量 %d\n", count, capacity);26    free(steps);27    return 0;28}
輸出
滿了,容量變成 4
滿了,容量變成 8
長度 6,容量 8

點單步,盯著堆:先是「8 位元組」的塊,放到第 3 個時換成「16 位元組」,放到第 5 個時換成「32 位元組」,舊塊一個個變灰。最後長度是 6、容量是 8,有兩格空著,等著下一個數。程式結束時只有最後那塊是活的,被 free 還掉了。

猜輸出猜錯也沒關係

容量從 2 開始,滿了就翻倍,放 5 個數。這段程式顯示什麼?

1#include <stdio.h>2 3int main(void) {4    int capacity = 2;5    int count = 0;6    for (int i = 0; i < 5; i++) {7        if (count == capacity) {8            capacity *= 2;9        }10        count++;11    }12    printf("%d %d\n", count, capacity);13    return 0;14}
練習 2

只留偶數

把 numbers 裡的偶數一個個放進會長大的陣列 evens(容量從 2 開始,滿了翻倍),最後顯示放進去的數,再顯示 長度 5,容量 8。

要顯示
8 6 4 10 2 
長度 5,容量 8
exercise2.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int numbers[8] = {3, 8, 6, 1, 4, 10, 7, 2};6    int count = 0;7    int capacity = 2;8    int *evens = malloc(capacity * sizeof(int));9    if (evens == NULL) {10        return 1;11    }12 13    for (int i = 0; i < count; i++) {14        printf("%d ", evens[i]);15    }16    printf("\n長度 %d,容量 %d\n", count, capacity);17    free(evens);18    return 0;19}
輸出
點「執行」或按 Ctrl+Enter
練習 3

修好它

這個會長大的陣列放到第 3 個數就越界了。找出判斷「滿了」那一行的錯,改好它,讓程式顯示 5 9 2 7 ,然後換行。

要顯示
5 9 2 7 
exercise3.c
1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int values[4] = {5, 9, 2, 7};6    int count = 0;7    int capacity = 2;8    int *list = malloc(capacity * sizeof(int));9    if (list == NULL) {10        return 1;11    }12    for (int i = 0; i < 4; i++) {13        if (count > capacity) {14            int *bigger = realloc(list, capacity * 2 * sizeof(int));15            if (bigger == NULL) {16                free(list);17                return 1;18            }19            list = bigger;20            capacity *= 2;21        }22        list[count] = values[i];23        count++;24    }25    for (int i = 0; i < count; i++) {26        printf("%d ", list[i]);27    }28    printf("\n");29    free(list);30    return 0;31}
輸出
點「執行」或按 Ctrl+Enter

為什麼要翻倍

每次只多要一格行不行?行,可是太慢。每次 realloc 搬家,都要把已有的數全部複製一遍。數一數放 1000 個數要搬幾次、一共複製多少個:

main.c
1#include <stdio.h>2 3int main(void) {4    int moves_one = 0;5    int copied_one = 0;6    int moves_double = 0;7    int copied_double = 0;8    int cap_one = 1;9    int cap_double = 1;10    for (int count = 1; count <= 1000; count++) {11        if (count > cap_one) {12            copied_one += cap_one;13            cap_one += 1;14            moves_one++;15        }16        if (count > cap_double) {17            copied_double += cap_double;18            cap_double *= 2;19            moves_double++;20        }21    }22    printf("每次加 1:搬 %d 次,複製 %d 個\n", moves_one, copied_one);23    printf("每次翻倍:搬 %d 次,複製 %d 個\n", moves_double, copied_double);24    return 0;25}
輸出
每次加 1:搬 999 次,複製 499500 個
每次翻倍:搬 10 次,複製 1023 個

這段程式沒有真的要記憶體,只是把兩種做法各自要搬幾次算出來。差別很大:每次加 1 要搬 999 次、複製將近 50 萬個數;翻倍只搬 10 次、複製 1023 個。數越多,差得越多。代價是最多會空著將近一半的格子,一般來說很划算。

猜輸出猜錯也沒關係

容量從 1 開始,滿了就翻倍,放進 10 個數。這段程式顯示什麼?

1#include <stdio.h>2 3int main(void) {4    int capacity = 1;5    int moves = 0;6    for (int count = 1; count <= 10; count++) {7        if (count > capacity) {8            capacity *= 2;9            moves++;10        }11    }12    printf("%d %d\n", moves, capacity);13    return 0;14}

寫成函式

每次放數都寫一遍 if 和 realloc 太長了,把它寫成函式 push。它要改 main 裡的長度和容量,所以這兩個傳位址(第 16 課);塊可能搬家,所以把(可能是新的)位址返回來:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4int *push(int *items, int *count, int *capacity, int value) {5    if (*count == *capacity) {6        int *bigger = realloc(items, *capacity * 2 * sizeof(int));7        if (bigger == NULL) {8            return items;9        }10        items = bigger;11        *capacity *= 2;12    }13    items[*count] = value;14    *count += 1;15    return items;16}17 18int main(void) {19    int prices[5] = {12, 8, 25, 4, 30};20    int count = 0;21    int capacity = 1;22    int *list = malloc(capacity * sizeof(int));23    if (list == NULL) {24        return 1;25    }26    for (int i = 0; i < 5; i++) {27        list = push(list, &count, &capacity, prices[i]);28    }29    for (int i = 0; i < count; i++) {30        printf("%d ", list[i]);31    }32    printf("\n長度 %d,容量 %d\n", count, capacity);33    free(list);34    return 0;35}
輸出
12 8 25 4 30 
長度 5,容量 8

點單步,進到 push 裡看:它的框裡 count 和 capacity 兩根箭頭指回 main 框裡的變數,items 指著堆上的塊。要不到記憶體時,push 什麼也不放,把原來的位址原樣還回去,main 的 list 不會丟。

*count += 1 不要寫成 *count++:++ 比 * 先算,那樣加的是指標本身,不是它指著的數。

單選

push 為什麼要把位址 return 回來,寫成 list = push(list, ...)?

這一課學會了

  • realloc(p, 新位元組數) 換一塊新大小的記憶體,原來的內容搬過去,返回新位址;之後只用新位址。
  • 先存進另一個指標再檢查 NULL:失敗時舊塊還在,直接寫 p = realloc(p, ...) 會把它丟掉。
  • 會長大的陣列記著長度(放了幾個)和容量(能放幾個);長度等於容量時就是滿了。
  • 滿了就把容量翻倍:比每次多一格搬得少得多。
  • 寫成函式時,長度和容量傳位址,塊的位址作為回傳值交回來;最後 free 一次。
第 22 課學完了嗎?第 22 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 23 課 · 15 分鐘結構體學 C 語言結構體:怎麼定義和初始化 struct、用點號訪問成員、賦值為什麼是複製、結構體陣列,以及把結構體傳給函式、從函式返回結構體。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。