gpt4 book ai didi

c - 几次重新分配后出现段错误 |结构数组

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:10 24 4
gpt4 key购买 nike

好吧,我正在实现一个具有结构形式数组的哈希表,如下所示:

    int SIZE = 769;
int entries=0;


typedef struct entry {
long id;
long n_article;
long id_rev;
long uni_rev;
} Entry;

typedef Entry * THash;


THash init_THash ()
{
int i;
THash t = (THash) malloc(SIZE*sizeof(struct entry));
//...
return t;
}

我有一个向哈希表添加内容的函数,如果条目超过 SIZE 的 70%,我会调整表的大小。

THash resize_THash (THash h){
int i;
int prime = SIZE*2;
h = (THash) realloc (h,(prime)*sizeof(struct entry));
//...
SIZE = prime;
return h;
}


void add_THash (THash h,long id, long idrevision){
int i,r=0;
if (entries > SIZE * 0.7) h=resize_THash(h);
//...
entries++;
}

哈希表的初始化是正确的,但问题是当我重新分配/调整大小 3 次时,停止工作,给我段错误;在这一点上,我尝试了一切,但我失败了。任何人都可以向我解释,为什么这个实现是错误的?

例如:在这个main中,如果条件是i<3000它有效,但如果它是 i<6000 , 不起作用。

int main()
{
int i;
THash t = init_THash();


for(int i=10;i<3000;i++){

add_THash(t,i,627604899);


}

printf("SIZE:%d\n",SIZE);
printf("ENTRIES: %d\n",entries);
return 0;
}

最佳答案

add_Thash 函数不返回新指针,让调用者使用现在无效的旧指针。

关于c - 几次重新分配后出现段错误 |结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43381627/

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