gpt4 book ai didi

c - 使用 realloc 函数时出错

转载 作者:太空宇宙 更新时间:2023-11-04 06:40:28 25 4
gpt4 key购买 nike

我有一个程序可以在哈希表的大小时动态增加哈希表的容量
它的桶超过了最大值。但是我被“* 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():”错误运行它。有人可以指出我的代码哪里出错了吗?我花了整个晚上都在调试这个东西,所以任何帮助都会非常好。为。。。道歉发布这么多行代码..

最佳答案

发生的事情是您分配了一个长度为capacity 的数组。然后,在显示为 capacity=capacity * 2 的行中将容量加倍。然后你在 for 循环中写下数组的末尾,因为数组只有你认为的一半长。

node **newlist=realloc(h->list,capacity*sizeof(node*));//array of length capacity
h->list=newlist;
....
capacity=capacity * 2;//oops, capacity is now twice as big as the array
for(i=temp;i<capacity;i++)
h->list[i]=calloc(1,sizeof(node));//and now we are writing off the end
}

您的代码中很可能还有其他错误。我看不到 capacity 变量是如何处理的。它是全局性的吗?它在哪里初始化?

此外,您在编辑中添加的代码显然是错误的。

 hashtable->list= calloc(1,sizeof(node *));
for (i = 0; i < 16; i++) {
hashtable->list[i] = calloc(1, sizeof(node));
}

此处您似乎将列表的初始容量设置为 1,但随后分配了 16 个值。显然 calloc 应该传递给 16 而不是 1

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com