我该如何免费提供此列表?

时间:2015-10-09 19:54:11

标签: c

请帮我完成一个项目,我不知道如何释放这个结构。 当我使用valgrind它说记忆丢失,因为我不知道如何使用免费

typedef struct list{
    int value1;
    int value2;
    struct list * next;
}List;

List *first;
List *last;


void create_list(){
    List *aux;
    aux = (List *) malloc(sizeof(List));
    first= aux;
    last= first;
}     

void insert(int a, int b){
    List *aux;
    aux = (List *) malloc(sizeof(List));
    aux->value1=a;
    aux->value2=b;
    last->next=aux;
    last= last->next;
    aux->next= NULL;
}

int main(int argc, const char* argv[]){

    create_list();
    insert(1,2);


    //How can i free?

}

2 个答案:

答案 0 :(得分:2)

怎么样

while(first != last) {
      List* temp = first->next;
      free(first);
      first = temp;
}
free(last);

答案 1 :(得分:1)

通过首先获取下一个节点来迭代所有节点,然后释放当前节点。完成后,释放列表结构本身......

相关问题