尝试分配内存时出现分段错误

时间:2019-05-24 06:19:31

标签: c segmentation-fault malloc

我正在尝试创建一个哈希表,其中哈希表的每个条目都是一个链表(存储桶)。尝试为哈希表的每个条目分配内存后,尽管我不明白为什么,但遇到了分段错误。使用valgrind之后,尽管我不明白为什么,但是我可以将错误定位到以下代码行。

new->buckets[i] = (bucket*)malloc(sizeof(bucket));

任何见解将不胜感激。谢谢。

typedef struct bucket bucket;
struct bucket {
  char *string;
  unsigned long int hash;
  bucket *next;
};
/* By convention, the empty bucket is NULL. */

typedef struct hash_table htbl;
struct hash_table {
  unsigned long int(*hash)(char*);
  bucket **buckets; /* an array of buckets */
  unsigned int n_buckets;
};

htbl *htbl_new(unsigned long int(*h)(char*), unsigned int sz)
{
  htbl* new = (htbl*)malloc(sizeof(htbl));
  new->hash = h;
  new->buckets = (bucket**)malloc(sizeof(bucket)*sz);
  new->buckets = NULL;
  new->n_buckets = sz;
  for(int i = 0; i < sz; i++){
    new->buckets[i] = (bucket*)malloc(sizeof(bucket));
  }
  return new;
}

1 个答案:

答案 0 :(得分:2)

问题是这一行:

new->buckets = NULL;

这会将指向上一行分配的数组的指针替换为空指针。结果,new->buckets[i]取消引用空指针并获得错误。

摆脱那一行。