0

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;
}
7
  • 2
    h=resize_THash(h) : This can't update caller side(t). Commented Apr 13, 2017 at 0:36
  • @BLUEPIXY what is t? Commented Apr 13, 2017 at 0:37
  • 1
    please post an minimal reproducible example Commented Apr 13, 2017 at 0:38
  • @xaxxon t of add_THash(t,i,627604899); at main Commented Apr 13, 2017 at 0:38
  • Also, did you actually malloc or calloc the original memory? If not, that's going to be a sack of hammers. Commented Apr 13, 2017 at 0:52

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

It was this! Oh really! But why does it works few times ? It's strange. Thank you very much!
@Puthz When you cross the street without looking both ways, sometimes you make it to the other side -- but sometimes you don't.
Well, amazing answer xD I have been all day trying understand the error, thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.