Puthz
Puthz

Reputation: 33

Segmentation Fault after few realloc | Array of Structs

Well, I'm implementing a hash table with array of struct form, like this:

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

I have a function that add something to the hash table and if the entries is more than 70% of the SIZE, I resize the table.

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

The init of the hash table is correct, but the problem is when I realloc/resize 3 times, stops working, giving me segmentation fault; At this point I tried everything and I failed. Anyone can explain me, why this implementation is wrong?

For example: in this main, if the condition is i<3000 it works, but if it's i<6000, doesnt work.

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

Upvotes: 0

Views: 199

Answers (1)

David Schwartz
David Schwartz

Reputation: 182769

The add_Thash function doesn't return the new pointer, leaving the caller to use the old, now invalid, one.

Upvotes: 2

Related Questions