everyone: I just come across an approach to allocate a 2D matrix in C. While practicing it, I'm confused about an unknown bug.
here is the function, first version:
//first version
static int ** my2DAlloc(int rows, int cols){
int ** array;
int * array_head;
int i;
int len = sizeof(int*)*rows + sizeof(int)*rows*cols + 1;
array = (int**)malloc( len );
memset(array, 0, len);
array_head = (int *) (array + rows);
for(i=0; i<rows; i++)
array[i] = array_head + i*cols ;
return array;
}
I don't have any problem with this version. However, I've tried to change the code a little, as the following:
//second version
static int ** my2DAlloc(int rows, int cols){
int ** array;
int * array_head;
int i;
int len = sizeof(int*)*rows + sizeof(int)*rows*cols + 1;
array = (int**)malloc( len );
memset(array, 0, len);
//array_head = (int *) (array + rows);
for(i=0; i<rows; i++)
array[i] = (int *) (array + rows + i*cols); // <--- the major difference
return array;
}
Regarding this second version, it seems fine to write data to the matrix and read data out. But when I try to free the allocated space, I get system error like:
free(): invalid next size (fast): 0x00000000020df010
It seems to be some memory error. But I could not figure out the problem. Could anyone help me out?
Thanks & Regards