我遇到了一个双重自由,我看不到它发生在哪里以下代码的目标是从链接列表中删除人员节点。

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--;
        }
    }

...

最佳答案

释放此人时,不会将前一个人的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;

09-08 08:56