C双免费问题

Mik*_*ike 1 c malloc free struct

我遇到了双倍的自由,我无法看到它发生在哪里.以下代码的目标是从链接列表中删除Person节点.

typedef struct person {
    char *first ;
    char *last ;
    char *location ;
    struct person *next_person ;
} person ;

struct person_list {
    int num_persons ;
    person *first_person ;
} person_list ;

extern struct person_list person_list ;

void free_person(person *person) {
    free(person->first);
    person->first = NULL;

    free(person->last);
    person->last = NULL;

    free(person->location);
    person->location = NULL;

    free(person);
    person = NULL;
}

...

    if (person_list.num_persons > 0) {
        while (person_list.num_persons > 0) {
            //Iterate to the end of the chain.
            cur_person = person_list.first_person;

            while (cur_person->next_person != NULL) {
                cur_person = cur_person->next_person;
            }

            free_person(cur_person);
            person_list.num_persons--;
        }
    }

...
Run Code Online (Sandbox Code Playgroud)

Wol*_*olf 5

当你释放这个人时,你不会将前一个人的next_person指针设置为NULL.因此,它指向释放的记忆,这就是你双重释放的原因.

您需要跟踪想要释放的人之前的人,并将其next_person指针设置为NULL.

编写循环的另一种更有效的方法是以下,它不会受到相同的错误:

    // Grab the first person
    cur_person = person_list.first_person;

    // Make sure there is someone to free
    while (cur_person != NULL) {
        // Keep track of who to free next
        nxt_person = cur_person->next_person;

        free_person(cur_person);

        // Get the next person in line
        cur_person = nxt_person;
    }

    // Didn't we just remove them all? Yes, we did.
    person_list.num_persons = 0;
    // Let's not forget to set that we have no one left
    person_list.first_person = NULL;
Run Code Online (Sandbox Code Playgroud)

  • 正如pmg所写,它只在函数内设置本地副本.您需要在函数外部将其设置为NULL,或者传递引用(这是C++功能,而不是C). (2认同)