簡體   English   中英

為什么我不能釋放每個內部都有指針的結構的指針“數組”?

[英]Why can't I free an pointer "array" of structs that each have pointers inside?

假設我們有這段代碼讀取文件中的 10 個空格分隔的字符串並將它們全部打印出來。 運行代碼時,我收到“heap-use-after-free”錯誤。 首先,我嘗試刪除 LINE A。這樣做給了我一個“嘗試在不是 malloc()-ed 的地址上釋放”錯誤。 接下來,我嘗試刪除 LINE B 並重新添加 LINE A。這樣做給了我“檢測到 memory 泄漏”錯誤。 我覺得我在這里有點束縛。 我如何正確釋放一切? (結構的“指針數組”和每個結構內的字符“指針數組”)

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct strs {
    char* s;
} str;

int main(int argc, char* argv[argc + 1]) {
    FILE* fp = fopen(argv[1], "r");
    
    //Malloc
    str* ex = (str*)malloc(10 * sizeof(str));
    for (int a = 0; a < 10; a++) {
        (ex+a)->s = (char*)malloc(sizeof(char) * 10);
    }

    //Scan
    for (int a = 0; a < 10; a++) {
        fscanf(fp, "%s ", (ex+a)->s);
    }

    //Print
    for (int a = 0; a < 10; a++) {
        printf("%s ", (ex+a)->s);
    }

    //Free
    for (int a = 0; a < 10; a++) {
        free((ex+a)->s); //LINE A
        free(ex+a); //LINE B
    }

    printf("\n");
    return 0;
}

free的調用次數應等於對malloc的調用次數,傳遞給free的內容應與從malloc返回的內容完全相同。

str* ex = (str*)malloc(10 * sizeof(str));
for (int a = 0; a < 10; a++) {
    (ex+a)->s = (char*)malloc(sizeof(char) * 10);
}

在這里,您為str的數組調用malloc一次,然后為每個數組成員中的s成員再調用 10 次。

for (int a = 0; a < 10; a++) {
    free((ex+a)->s); //LINE A
    free(ex+a); //LINE B
}

循環內的第一行很好。 第二個不是因為ex+a不是從malloc返回的值(第一次迭代除外)。

您需要釋放循環內的s成員,然后在循環后釋放數組。

for (int a = 0; a < 10; a++) {
    free((ex+a)->s);
}
free(ex);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM