-2

Pls help me to finish a project i dont know how i can free this struct. When i use valgrind it says memory lost because i dont know ho to use free

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?

}
  • Don't cast malloc() in C – Michi Oct 09 '15 at 19:57
  • 1
    Possible duplicate of [How do I free memory in C?](http://stackoverflow.com/questions/9069205/how-do-i-free-memory-in-c) – Łukasz Oct 09 '15 at 20:03
  • @NoOP's http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – PC Luddite Oct 09 '15 at 20:15
  • @Łukasz I don't think the link you mention applies here. It is about de-allocating an array (which can be done in one go), whereas the OP here needs to delete all nodes of a linked list one by one. – WhiteViking Oct 09 '15 at 21:32

3 Answers3

2

How about

while(first != last) {
      List* temp = first->next;
      free(first);
      first = temp;
}
free(last);
PC Luddite
  • 5,883
  • 6
  • 23
  • 39
1

just iterate through all the nodes by first getting the node's next, and then free the current node. When done, free the list struct itself...

ByoTic
  • 103
  • 8
0

You could use a recursive function like the one below.

free_list(List* input) {
    if(input == NULL)
        return;
    if(input->next == NULL) {
        free(input);
    } else {
        free_list(input->next);
        free(input);
    }
 }
jayant
  • 2,349
  • 1
  • 19
  • 27
  • I tend to avoid recursion when possible. It can take up a lot of stack space, especially if it's a really big list. – PC Luddite Oct 09 '15 at 20:14
  • Thanks! I tried to comment on your solution regarding the ++ operator but didn't have enough reputation :( – jayant Oct 09 '15 at 20:24
  • 1
    @jayant I edited my answer almost immediately after posting it because I realized using `++` was wrong. – PC Luddite Oct 09 '15 at 20:27