![](/img/trans.png)
[英]How can I free an array of pointers where each pointer points to an address of a string which I allocated inside of a function?
[英]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.