[英]Correct way of doing free() in C
我有具有結構數組的以下代碼。 每個數組元素都有一個字符串副本。 我的問題是在完成所有操作后執行free()的正確方法是什么:
1 #include <string.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4
5 typedef struct testStruct {
6 char *val;
7 int index;
8 } testStruct;
9
10
11 int main()
12 {
13 char *value = "hello world";
14 int NMAX = 10;
15 testStruct *test_array = (testStruct *) malloc(NMAX * sizeof(testStruct));
16
17 int i;
18 for (i = 0; i < NMAX; i++)
19 {
20 test_array[i].val = strdup(value);
21 test_array[i].index = i;
22
23 printf("added %d \n", i);
24 }
25
26 for (i = 0; i < NMAX; i++)
27 {
28 // free(test_array[i].val); /* is it okay not to free the val field? */
29 }
30 free(test_array); /* only do this free() on the entire array */
31
32 }
分配給每個“ val”的內存在執行結束時釋放嗎?
您需要釋放val
字段,因為strdup
生成動態分配的字符串的新副本。
為了避免很多堆分配,如果您有字符串長度的上限,則無需使用strdup
。 只需在結構本身內部聲明一個靜態char數組:
const size_t MAX_LENGTH = 32;
typedef struct TestStruct
{
char val[MAX_LENGTH];
..
}
並使用strncpy
復制內容。
另外,不需要將malloc返回的指針強制轉換為指定的類型,因為在C中, void*
可以轉換為其他類型,而無需顯式的向下轉換(在C ++中不是這樣)。
請記住,一旦釋放了指針(地址),就無法通過該地址訪問內存。 strdup()為每個test_array[i].val
分配內存(並復制字符串),因此首先在循環中釋放它,然后釋放test_array
:
for (i = 0; i < NMAX; i++)
{
free(test_array[i].val); // free memory allocated by `strdup(value);`
}
free(test_array); // free by malloc() @ line number 15
這類似於內存分配步驟的相反順序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.