【问题标题】:Segmentation Fault after few realloc | Array of Structs几次重新分配后的分段错误 |结构数组
【发布时间】:2017-09-08 22:45:06
【问题描述】:

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

    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;
}

【问题讨论】:

  • h=resize_THash(h) : 这不能更新调用方(t)。
  • @BLUEPIXY t 是什么?
  • @xaxxon t of add_THash(t,i,627604899); main
  • 另外,您实际上是 malloc 还是 calloc 原始内存?如果没有,那将是一袋锤子。

标签: c arrays segmentation-fault hashtable realloc


【解决方案1】:

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

【讨论】:

  • 就是这个!哦真的吗!但为什么它工作几次?真奇怪。非常感谢!
  • @Puthz 当你过马路时不看两边,有时你会到另一边——但有时你不会。
  • 嗯,很棒的答案 xD 我整天都在尝试理解错误,非常感谢!
猜你喜欢
  • 2019-09-16
  • 2020-08-15
  • 2017-12-13
  • 2021-10-11
  • 2011-09-04
  • 2021-06-12
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
相关资源
最近更新 更多