Hi all,
I'm trying to readin a 2D array of long integers, of unknown row and col size to start with.
Here is the relevant part of the code
Here is the memory map of what the compiler allocatesCode:... ... long int **datacols; colstofindcount=6; datacols=(long int **)malloc(colstofindcount*sizeof(long int *)); if (datacols==NULL){ printf("Unable to allocate memory to datacols\n"); exit(1); } colslen=26416; for(i=0;i<noofcolstofind;i++){ *(datacols+i)=(long int *)malloc(colslen*sizeof(long int)); if (*(datacols+i)==NULL){ printf("Unable to allocate memory\n"); exit(1); } } /* end of for loop allocating memory to all cols*/
datacols= 0x94f5968
I expect datacols to be allocated 24 bytes as sizeof(long int) on my machine is 4 bytes
So I expect the memory from 0x94f5968 to 0x94f598c to be allocated, as is shown below.
(datacols+0) 0x94f5968
(datacols+1) 0x94f596c
(datacols+2) 0x94f5970
(datacols+3) 0x94f5974
(datacols+4) 0x94f5978
(datacols+5) 0x94f597c
If we see the blocks of memory allocated in the for loop, I see
*(datacols+0) 0x94f5978
*(datacols+1) 0x950f638
*(datacols+2) 0x95292f8
*(datacols+3) 0x9542fb8
*(datacols+4) 0x955cc78
*(datacols+5) 0x9576938
Please note that the first block allocated starts at 0x94f5978 which has already been allocated for the malloc call before the for loop. The compiler for some reason seem to reserve only 12 bytes instead of 24.
Can some one explain / help. I'm wondering what I'm doing wrong.
I'm running gcc4.0.1 on Fedora Core 4
I'm able to duplicate the same error on gcc running in Cygwin.
Thanks
Senthil
PS: Please note that colstofindcount and colslen are being calculated at runtime, and I have just put in the numbers for this example.