Hash table in C, array of pointers

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Hash table in C, array of pointers on this date .

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

  • Specify the types of function arguments.
  • Allocate for the array index_table.
  • Remove extra malloc() whose result is overwritten to NULL right away to eliminate memory leak.
  • Use correct syntax for for: use ; instead of ,.
  • Return the created object.
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 */