tags:

views:

72

answers:

2

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!

+5  A: 

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;
}
ZoogieZork
That makes sense. Thank you very much
Appu
+2  A: 

also its not clear if you array is meant to contain structs or pointers to structs

struct symbol *st[PARSER_HASH_SIZE];

says its an array of pointers to structs. But then you say

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

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

This is treating the entries like structs

to clear the array do

for (int i = 0; i < PARSER_HASH_SIZE; i++)
{
    st[i] = 0;
}
pm100
It is meant to contain pointers to structs. Can you tell me how to initialize it properly?
Appu