Trufflezz68
Trufflezz68

Reputation: 29

Invalid read of size 8 C + valgrind

Valgrind is outputing this

==7558== Invalid read of size 8
==7558==    at 0x109049: delete_all_employees (emp.c:300)
==7558==    by 0x108BCB: main (rpt.c:37)
==7558==  Address 0x5232760 is 0 bytes inside a block of size 
40 free'd
==7558==    at 0x4C30D3B: free (in 
/usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)   
==7558==    by 0x108E15: free_emp (emp.c:175)
==7558==    by 0x109044: delete_all_employees (emp.c:299)
==7558==    by 0x108BCB: main (rpt.c:37)
==7558==  Block was alloc'd at
==7558==    at 0x4C31B25: calloc (in                     
/usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7558==    by 0x108DAE: new_emp (emp.c:143)
==7558==    by 0x108C73: add_employee (emp.c:65)
==7558==    by 0x108FB9: load_employees (emp.c:272)
==7558==    by 0x108BA2: main (rpt.c:28)

And the function that its calling the error at is this

void delete_all_employees( void ) {
    Employee *emp = employees;

    while( emp ) {
        free_emp(emp);
        emp = emp->next;

    }
}

I don't know why this is giving me an invalid read size of 8

Upvotes: 2

Views: 3959

Answers (1)

dbush
dbush

Reputation: 223689

You're free'ing emp, then trying to read from it. That's what valgrind is complaining about.

Save the pointer to be free'ed in a separate variable before incrementing emp, then free the temp.

while( emp ) {
    Employee *tmp = emp;
    emp = emp->next;
    free_emp(tmp);
}

Upvotes: 5

Related Questions