0

I am a beginner and am having a really hard time with dynamic memory allocation. If anyone can help me with this problem, I would be really grateful.

I allocate some memory using malloc to an array Node using:

struct nodeT {
int id;
nodeT *parent, *T1, *T2;
};

struct nodeT* T;
T =  (struct nodeT*) malloc( 256*sizeof(struct nodeT) );

Then in order to reference T, I use a an array of pointers to T, call it Tptr:

struct nodeT** Tptr;
Tptr = (struct nodeT**) malloc( 256*sizeof(struct nodeT*) );

In my code, I fill data in T and then I set *Tptr = T iteratively as follows:

nodeT* s = &T[ 1*21 ];
s->id=23;
s->T1=...
s->T2=...
s->parent=...

and then

sptr = &Tptr[ 1*21 ];
*sptr=s;
and it works fine.

But sometimes, when I call realloc to increase the size of T, and then I check *sptr, it is no longer valid, I get a segmentation fault at runtime. I think the realloc may sometimes move the entire memory block to a new location, while the *sptr keeps pointing to the old location.

Any idea how can I update all Tptr after every realloc.

If I use a big size of T from the beginning and disable realloc for T, everything works fine. But I want it to work with dynamically increasing array sizes.

Best Regards Wajahat

Wajahat
  • 453
  • 5
  • 8

1 Answers1

0

Your call to malloc sets T. When you call re-alloc you can not assume that T will be in the same place Since Tptr is set Tptr = T after calling

T =  (struct nodeT*) malloc( 256*sizeof(struct nodeT) );

your array of pointers TPtr needs to be re-populated after every realloc on T. If you don't want to do this yourself, use vectors rather than arrays and realloc

camelccc
  • 2,847
  • 8
  • 26
  • 52