简体   繁体   English

释放动态分配的数组是否与释放链表相同?

[英]Is freeing a dynamically allocated array same as freeing a linked list?

Suppose I have a struct that looks like this: 假设我有一个看起来像这样的结构:

typedef struct node{
char **word_ptrs;
int value;
struct node *next;
} Node;

and I have dynamically allocated spaces for the linked list, as well as the word_ptrs within this struct. 并且我为链表以及该结构中的word_ptrs动态分配了空间。

For example: 例如:

Node *head = malloc(sizeof(Node)); // not important, what I care is not this node.
head->word_ptrs = malloc(10 * sizeof(Node)); // I care about this.

My question is: I know how to free the linked list, but I feel confused when I try to free the dynamically allocated array. 我的问题是:我知道如何释放链表,但是当我尝试释放动态分配的数组时,我感到困惑。 When I try to free the array above, should I just directly free the entire array? 当我尝试释放上面的数组时,是否应该直接释放整个数组? Or I should go to free every single char * within that array? 还是我应该释放该数组中的每个单个char *?

Thanks. 谢谢。

You should only pass to free what was returned from malloc . 您应该只free malloc返回的内容。

In this case, you make one allocation for an array of char * , so you do a single free to clean it up. 在这种情况下,您为char *数组进行了一次分配,因此您可以一次free地清理它。 Also, the amount of space you're allocating is 10 * sizeof(Node) , but it should be 10 * sizeof(char *) . 另外,您分配的空间量为10 * sizeof(Node) ,但应为10 * sizeof(char *)

That depends on where those pointers came from, and who owns them. 这取决于这些指针来自何处以及谁拥有它们。

If they were dynamically allocated and the node owns them, then you should free them before freeing the array. 如果它们是动态分配的,并且节点拥有它们,则应在释放数组之前释放它们。
If they were dynamically allocated but owned elsewhere, their respective owners should free them later. 如果它们是动态分配的,但在其他地方拥有,则它们各自的所有者应在以后释放它们。
If they were not dynamically allocated, you mustn't free them at all. 如果它们不是动态分配的,则绝对不能释放它们。
If you have a combination of the three, you're in trouble. 如果您将这三者结合起来,那就麻烦了。

You should also allocate it with sizeof(char*) , or sizeof(*head->word_ptrs) , not sizeof(Node) . 您还应该使用sizeof(char*)sizeof(*head->word_ptrs)而不是sizeof(Node)分配它。

Although, if the size is always ten, you might as well use an array: 虽然,如果大小始终为十,则最好使用一个数组:

typedef struct node{
    char *word_ptrs[10];
    int value;
    struct node *next;
} Node;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM