我有一个程序可以动态地增加哈希表的容量
其桶超出最大值。但是我被一个“*glibc”击中了
检测到*realloc():“当我尝试运行代码时出错。
有人能帮我吗?很抱歉在这里放置了这么多代码,但我真的需要
帮助。

  /* structure for the hashtable containing an array of nodes */

  typedef struct Hashtable hashtable;
  struct Hashtable {
  struct node **list;
  };


  /* the function which resizes the hashtable and re-arranges the values according to
     new capacity */

  void reSize(hashtable *h)
   {

    int i;
    node **newlist=realloc(h->list,2*capacity*sizeof(node*));
    h->list=newlist;
   int temp=capacity,index;
   capacity=capacity * 2;
    for(i=temp;i<capacity;i++)
    h->list[i]=calloc(1,sizeof(node));
    }


    /* mystructure init */
    struct hashtable *mystruct_init()
    {
     int i;
     hashtable *hashtable =calloc(1, sizeof(*hashtable));

     // loop through and allocate memory for each element in list
     hashtable->list= calloc(1,sizeof(node *));
      for (i = 0; i < 16; i++) {
       hashtable->list[i] = calloc(1, sizeof(node));
    }

   return hashtable;
    }
   /* in my main function */

    hashtable *h1=(hashtable *) mystruct_init();
    hashtable *h2=(hashtable *) mystruct_init();

当我尝试时,我得到这个“*glibc detected*/compareDocs:realloc():”错误
运行它。有人能指出我的代码哪里出错了吗??我花了
整晚都在试着调试这个东西,所以任何帮助都是非常好的。对不起
发布这么多代码行。。

最佳答案

在mystruct_init()函数中,您只为列表分配了一个node *

hashtable->list= calloc(1,sizeof(node *));

然后在分配的内存结束时取消对元素的引用:
for (i = 0; i < 16; i++) {
   hashtable->list[i] = calloc(1, sizeof(node));

此外,在reSize()函数中,您使用了变量容量,但似乎没有在任何地方定义。这是你真正的密码吗?如果是,容量的价值是什么?
编辑:您可能应该使init函数中的代码如下所示:
struct hashtable *mystruct_init()
{
    int i;
    hashtable *hashtable =calloc(1, sizeof(*hashtable));

    // loop through and allocate memory for each element in list
    hashtable->list= calloc(capacity, sizeof(node *));
    for (i = 0; i < capacity; i++) {
       hashtable->list[i] = calloc(1, sizeof(node));
    }
    return hashtable;
}

注意,我在调用calloc()时使用了capacity,并在下面的for循环中将其用作控制值。

关于c - 使用realloc函数时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9115512/

10-14 22:07
查看更多