dynamically realloc 2D array

Hello,

I would like to realloc a 2D array. I have a counter, itime, it increases each step. Each step, I would like to reallocate my array, keeping the old values, and add new values to the array. When itime=1, I use only malloc, because it is allocated for the first time. When itime increases (e.q. itime=2), realloc comes into process. In the realloc process the GUI crashes. I will be very thankful if somebody can tell me the reason of the crash.


int itime;
char ** solpointer;

itime = 1;

do {
if( itime == 1 ) {
solpointer = (char**)malloc(sizeof(char*) * itime);
solpointer[itime-1] = (char*)malloc(sizeof(char) * 32);
}
else {
solpointer = (char**)realloc(solpointer, sizeof(char*) * itime);
solpointer[itime-1] = (char*)malloc(sizeof(char) * 32 );
}

itime = itime + 1;
} while( err > eps );
1) Your loops as written is infinite and will exhaust memory quickly.
2) Many allocations and reallocarions of small amounts of memory has detrimental effect on perfomance
3) You never check pointers returned by malloc/realloc. They should be checked.
4) sizeof(char*) is nit strictly guaranteed to be equaly to sizeof(char**)
Thank you MiiNiPaa,

But my loop is not infinite. It is only a part of the code. After few cycles, the loop ends. Not many allocation occurs.
What kind of information I can get by checking the pointers?
Can you please explain more about point 4?
Can you please explain more about point 4?
Disregard that, I misread your code.

What kind of information I can get by checking the pointers?
If allocation fails, it returns null pointer.

What else to check:
1) Does GUI works asynchronously? If so, it might access memory in the moment of reallocation.
2) Are you sure that nothing stores pointers to your array and only works with it through solpointer?
Topic archived. No new replies allowed.