Thread: hashtable with seg fault

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    3

    hashtable with seg fault

    Hi!
    I don't know why I got seg fault when I'm implementing the *creattable() function.

    Code:
    #define INIT_BUCKETS 5
    
    typedef struct node {
      char *key;
      char *value;
      struct node *next;
    } Data_pair_node;
    
    typedef Data_pair_node * Hash_bucket;
    
    struct hash_table {
      int key_ct;
      int bucket_ct;
      Hash_bucket *buckets;
    };
    
    typedef struct hash_table Table;
    
    
    
    Table *create_table(){
      Table *t;
      int index;
    
      t = malloc(sizeof(Table));
    
      if(t == NULL){
          return NULL;
      }
    
      (*t).buckets = malloc(sizeof(Data_pair_node) * INIT_BUCKETS);
      for(index = 0; index < INIT_BUCKETS; index++){
          *(*t).buckets++ = malloc(sizeof(Data_pair_node));
      }
    
      /*gdb tells me the seg fault starts right here, but I dont know what's wrong?*/
      for(index = 0; index < INIT_BUCKETS; index++){
          (*(*t).buckets[index]).key = malloc(sizeof(char));
          (*(*t).buckets[index]).value = malloc(sizeof(char));
    
      }  for(index = 0; index < INIT_BUCKETS; index++){
          (*(*t).buckets[index]).key = '\0';
          (*(*t).buckets[index]).value = '\0';
    
      }
     
      (*t).key_ct = 0;
      (*t).bucket_ct = INIT_BUCKETS;
    
      return t;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > *(*t).buckets++ = malloc(sizeof(Data_pair_node));
    You're modifying your pointer!

    Also, why not use the -> operator?

    try
    t->buckets[index] = malloc(sizeof(Data_pair_node));
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  3. weird seg fault
    By Vermelho in forum C Programming
    Replies: 3
    Last Post: 05-10-2008, 08:27 PM
  4. Seg Fault Problem
    By ChazWest in forum C++ Programming
    Replies: 2
    Last Post: 04-18-2002, 03:24 PM
  5. oh me oh my hash maps up the wazoo
    By DarkDays in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2001, 12:54 PM