malajedala
malajedala

Reputation: 907

realloc of two-dim pointer in function in C

I am using a two-dim pointer to a structure to store a list of addresses I use later.

int max=100;
int i=0;
my_structure** addresses=malloc(sizeof(my_struct*)*max);
if (addresses == NULL) //Throw error

do_something_and_fill_list(&i, &max, addresses);

And now when I use it in a function, where the list will be filled, after I do a realloc, I get a segmentation fault and I don't know what the problem is:

void do_something_and_fill_list(int* i, int* max, my_structure** addresses) {

     (*i)++;
     //do something and add elements
     if (*i==*max) {
       (*max)*=2;
       addresses=realloc(addresses, sizeof(my_struct*)*(*max));
      //so from here it does not work any more
     }
}

Upvotes: 0

Views: 72

Answers (1)

tkausl
tkausl

Reputation: 14269

First Problem:

addresses=realloc(addresses, sizeof(my_struct*)*(*max));

If it fails to reallocate you'll not notice.

my_structure** tmp = realloc(addresses, sizeof(my_struct*)*(*max));
if(!tmp) {
    printf("Unable to allocate more memory");
    exit(1); //Or just return, free addresses or whatever.
}
addresses = tmp;

Second problem:

void do_something_and_fill_list(int* i, int* max, my_structure** addresses)

You're passing a my_structure-ptr-ptr by value, in the function you (may) reallocate this my_structure-ptr-ptr, but from the outside, the new ptr will not be visible. You have to pass it (like every other parameter) by pointer, so you'd pass a my_structure-ptr-ptr-ptr

void do_something_and_fill_list(int* i, int* max, my_structure*** addresses)
//Call:
do_something_and_fill_list(&i, &max, &addresses);
//Use:
*addresses = realloc(*addresses, sizeof(my_struct*)*(*max));

Upvotes: 1

Related Questions