I am trying to implement a hash table in C. We hash the value and we do modulo the size of the table to obtain the index i.
Each entry of the table is a linked list. We then put the value in the i position in the corresponding list.
For that i strated by creating a struct list :
struct list {
char val;
struct list *next;
}
So an empty list is just the pointer NULL.
Then i need to create my struct table :
struct hash_table {
uint32_t size;
struct list *index_table[];
}
Now i want to create an empty hash table of size N. For that i create a function :
struct hash_table* createTable(N) {
struct hash_table* table = malloc(sizeof(struct hash_table));
table->size = N;
for (int i=0, i<N, i++) {
table->index_table[i] = malloc(sizeof(struct list))) ;
table-> index_table[i] = NULL /*Empty list*/;
}
}
However i get the error from valgrind about invalid read of size 8...
Thanks for your help. I am still a beginner in C so any idea might be helpfull.
You shoudld
index_table
.malloc()
whose result is overwritten to NULL
right away to eliminate memory leak.for
: use ;
instead of ,
.struct hash_table* createTable(uint32_t N) { /* specify the type of argument */
/* add size of the table */
struct hash_table* table = malloc(sizeof(struct hash_table) + sizeof(table->index_table[0]) * N);
table->size = N;
for (uint32_t i=0; i<N; i++) { /* use correct for syntax */
/* remove malloc() that is causing memory leak */
table-> index_table[i] = NULL /*Empty list*/;
}
return table; /* return what is created */
}