简体   繁体   中英

freeing an allocation in a struct inside a struct

When I try to free an allocation in a struct inside a struct, I get an error. How can I fix it?

typedef struct card
{
    char* sign;
    char* color;
    int number;
    char* name;
}card;

typedef struct deck
{
    card data;
    deck* next;

}deck;

deck* deleteHead(deck* head)
{ 
    deck* curr = head;
    if (head==NULL)
        return head;
    curr=curr->next;
    if(head->data.color!=NULL)
        free(head->data.color);//error
    if(head->data.name!=NULL)
        free(head->data.name);//error
    if(head->data.sign!=NULL)
        free(head->data.sign);//error
    free(head);//ok
    return curr;
}

when I'll delete the errors and only freeing the head - it'll work, but when I'll try to delete the allocations inside the head, I'll get a run time error. How can I solve this? Thank you in advance.

You probably did not initialize the pointers in the card structure. These should either be initialized to NULL or to a pointer to memory allocated by malloc , calloc or strdup .

Also note that you don't need to test pointers against NULL before calling free() . free(NULL); will gracefully return immediately, it is legal to call free with NULL . Incidentally it is also legal in C++ to delete a null pointer.

The function can be further simplified this way:

deck *deleteHead(deck *head) { 
    deck *next = NULL;
    if (head != NULL) {
        next = head->next;
        free(head->data.color);
        free(head->data.name);
        free(head->data.sign);
        free(head);
    }
    return next;
}

The function free can only de-allocate a block of memory previously allocated by a call to malloc, calloc or realloc. Your code will run without any runtime error if you initialize it properly. Here's a sample code:

int main()
{
    deck* root = (deck*)malloc(sizeof(struct deck));
    root->card.color = strdup("color");
    root->card.name = strdup("name");
    root->card.sign = strdup("sign");
    root->card.number = 2;
    root->next = NULL;
    root = deleteHead(root);
    return 0;
}

And also there is a slight correction in your code:

typedef struct deck
{
    card data;
    struct deck* next;

}deck;

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