Free function activates a breakpoint

Viewed 54

I'm trying to call the free function to deallocate nodes from a linked list, but whenever I try to do so the IDE (CLion) stops the program and gives me a SIGTRAP (Trace/breakpoint trap).

Here is the linked list:

struct node{
    int score;
    int index;
    struct node* nextNode;
};

typedef struct node* List;

Now the functions that initalizes and links the list:

List list= malloc(sizeof(List));
list->index=-1;
list->score=-10;
list->next=NULL;
min++;  min--;
List temp;
for(int i=sizeGrafi-1; i>0; i--){
     temp= malloc(sizeof(List));
     temp->index=i;
     temp->score=-10;
     temp->next=list;
     nodiDaVisitare=temp;
}

And here's the funcition that should delete and deallocate a node (to avoid useless code I'll just post the case in which the node to remove is the head):

List removeNode(List list){
    Lista temp= malloc(sizeof(List));
    temp=list;
    list=list->next;
    free(temp);
    return list;
}

I tried looking at similiar questions, but I couldn't find what is wrong with my code. The crash happens when the free function gets called.

EDIT: I followed the advice to remove the typedef

typedef struct node* List;

,rewrite all lists as Node*, with Node defined as:

typedef struct node{
    int punteggio;
    int indice;
    struct nodo* successivo;
}Node;

and using the right size (i.e. sizeof(Node)) in mallocs. Now the function free doesn't seem to give any problems. Thank you all.

1 Answers
    Lista temp= malloc(sizeof(List));
    temp=list;
    list=list->next;

You malloc memory and store the reference to it in temp. Then you assign temp with list. The previous value is lost.

Then you try to free that pointer - thus problems with free.

BTW that function makes no sense at all. It is hard to understand what you want to achieve.

Additionally, never hide the pointers behind typedefs.

Related