0

I came across uthash, a opensource library for hash table implementation in c programming language. I found it good and decided to use it in my project. Right now I am stuck with one issue .

I stared with small implementation where I created a hash table and I am trying to add integer array as a key in the hash table. Integer array is of size 26. Below is my structure

struct record
{
  int key[26];
  UT_hash_handle hh;
};

When I am trying to add more than one entry in the hash table I am getting segmentation fault.

Below is my implementation

   struct record *hash_p = NULL, *op=NULL, *p=NULL;
   struct record find;

   //first entry
   hash_p = (struct record *)malloc(sizeof(struct record));
   memset(hash_p,0,sizeof(struct record));

   //filling some random index
   hash_p->key[0] = 2;
   hash_p->key[3] = 3;
   hash_p->key[7] = 7;
   HASH_ADD(hh, op, key, sizeof(int)*26, hash_p);

   //Adding second entry 
   hash_p = (struct record *)malloc(sizeof(struct record));
   memset(hash_p,0,sizeof(struct record));

   //filling some random index
   hash_p->key[0] = 2;
   hash_p->key[3] = 3;
   hash_p->key[7] = 8;
   HASH_ADD(hh, op, key, sizeof(int)*26, hash_p);

   //find the key in hash table
   memset(&find,0,sizeof(struct record));
   hash_p = NULL;
   find.key[0] = 2;
   find.key[3] = 3;
   find.key[7] = 7;
   HASH_FIND(hh, op, &find.key[0], sizeof(int)*26, hash_p);
   if (hash_p) printf("found\n"); else printf("Not found");

Am I adding second entry in correct way? How can I add multiple records in my above hash. Can anyone please help

sachu
  • 11
  • 2
  • Which line is giving you segfault? – Fra93 Jul 07 '22 at 12:37
  • And since that, by looking at the library, the macro is expanded quite few times, can you debug till the instruction that gives the segfault? – Fra93 Jul 07 '22 at 13:23
  • One thing that I see is different from the example is that when they call `HASH_ADD` the fourth parameter is `sizeof(record_key_t)` and you instead use the size of the array, not the whole struct. Does changing it to `sizeof(struct record)` makes any difference? – Fra93 Jul 07 '22 at 13:24

0 Answers0