C. Rib
C. Rib

Reputation: 390

C - Linked lists: free() function is deleting my head node; how do I use free() correctly?

I need to make a function that drops the first n nodes of a linked list in c and returns the number of removed nodes. If the list is smaller than n, it should become empty. Also, I cannot use recursvity.

With the code as it is right now, it works but I am not freeing the memory of the "deleted" nodes. If I uncomment the part that should free the memory, I get this error on codeboard.io:

Input: 5 + [ 61 62 63 64 65 66 ]
Output: expected 5 + [ 66 ]
        obtained 5 + [19333664 ]

That random number seems to be that it is accessing "junk" in memory. How do I correctly free the nodes I don't use anymore?

Code inside listas.h:

typedef struct lligada {
    int valor;
    struct lligada *prox;
} *LInt;

LInt newLInt (int, LInt);

int drop (int, LInt *);

Code inside listas.c

#include <stdlib.h>
#include "listas.h"

int drop (int n, LInt *l){
    int count = 0;
    LInt *aux;
    while(n>0 && (*l)!=NULL){
          n--;
          count++;
          //aux = &((*l));
          *l = (*l)->prox;
          //free(*aux);
    }
return count;
}

Codeboard link to exercise: https://codeboard.io/projects/16259

Upvotes: 0

Views: 117

Answers (2)

s7amuser
s7amuser

Reputation: 847

Note that LInt it defined to be a pointer to struct lligada. Therefore, the l parameter to the drop function is a pointer to a pointer to struct lligada. Let's call the LInt variable that l points to list_head.

So, the line:

aux = &((*l));

Is actually assigning to aux the address of list_head and not the struct lligada that list_head points to.

Thus, the solution will be to define aux as LInt and then do:

aux = *l;
*l = (*l)->prox;
free(aux);

Hope that helps.

Upvotes: 1

C. Rib
C. Rib

Reputation: 390

I reached a similar solution to that of jboockmann by not making aux a double pointer, but as I said under his solution I don't understand what and why that was wrong.

int drop (int n, LInt *l){
    int count = 0;
    LInt aux;
    while(n>0 && (*l)!=NULL){
          n--;
          count++;
          aux = *l;
          *l = (*l)->prox;
          free(aux);
        }
    return count;
}

Upvotes: 1

Related Questions