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