Invalid read of size 8 - Valgrind + C

Navaneeth K N picture Navaneeth K N · Oct 27, 2010 · Viewed 95.8k times · Source

Valgrind reports error Invalid read of size 8 in the following code.

I have an array declared like,

struct symbol *st[PARSER_HASH_SIZE];

When my program is initialized, all the elements in this array are initailzied as 0.

memset(&st[0], 0, sizeof(st));

My program creates instances of struct symbol and inserts into the above array depending on the hash value. So few of the elements in this array will be NULL and others will be valid value.

The following code tries to delete the allocated items and valgrind complains at the line, sym = st[i]; sym != NULL; sym = sym->next

struct symbol *sym = NULL;

/* cleaning the symbol table entries */
for(i = 0; i < PARSER_HASH_SIZE; i++) {
    for(sym = st[i]; sym != NULL; sym = sym->next) { /* <-- Valgrind complains here */
        free(sym);
    }
}

I am trying to understand the reason for this error.

Any help would be great!

Answer

ZoogieZork picture ZoogieZork · Oct 27, 2010

The problem is that you're freeing the sym, then trying to access a value from the (now-freed) data: sym->next.

You probably want something like this for the inner loop:

struct symbol *next_sym = NULL;

for(sym = st[i]; sym != NULL; ) {
    next_sym = sym->next;
    free(sym);
    sym = next_sym;
}