0
votes

Im writing a program that translates a file, and for each translation made it creates a node in a linked list and later prints those linked lists to an output file, the program can take few files from command line, so between the file swaps I need to reset the linked. this is the struct that I need to free:

typedef struct symbol{
char symName[32];
unsigned int address;
unsigned int external:1;
unsigned int entry:1;
unsigned int unknown:1;
unsigned int line_num;
struct symbol *next;
}symbol;

I used this code for reseting (all the nodes are malloc allocated):

void freeLists(symbol *sym_h){

symbol *sym_temp;

while(sym_h != NULL)
{
    sym_temp=sym_h;
    sym_h = sym_h->next;
    free(sym_temp);
}}

this is the list before reseting(the format is "memory address of pointer","counter","temp->adress","temp->symName"):

x7ff24c405790 0 0 fn1
0x7ff24c4057d0 1 100 MAIN
0x7ff24c405830 2 102 LIST
0x7ff24c405890 3 104 fn1

but right after the free function if I try to print the list this is the output I get:

x7ff24c405790 0 0 
0x7ff24c4057d0 1 100 MAIN
0x7ff24c405830 2 102 ??$?
0x7ff24c405890 3 104 ??$?

it seems that free only resets the symName string... I have 2 questions basically:

  1. shouldn't free remove the entire struct? or at least delete all it content? 2.how come that after free was used I can't still travers the linked list?
  2. if I delete the this function entirely, and just set the linked list head to be NULL the program runs fine, if I use the free function I get segmantation fault how doest that happen?

I will add more code snippets if needed. thank a lot!

1

1 Answers

0
votes

What is sym_h? You passed sym_head so use it:

void freeLists(symbol *sym_head){
    symbol *sym_temp;

    while(sym_head != NULL)
    //    ^^^^^^^^
    {
        sym_temp=sym_head;
        sym_head = sym_head->next;
        free(sym_temp);
    }
}

free deallocates memory for a single node, so you can't use your list after freeLists is called. If you remove this function and just set list's head to NULL you won't deallocate allocated memory and that a memory leak.