简体   繁体   中英

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.

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?

Thanks.

You should only pass to free what was returned from malloc .

In this case, you make one allocation for an array of char * , so you do a single free to clean it up. Also, the amount of space you're allocating is 10 * sizeof(Node) , but it should be 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) .

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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