I’m trying to create a multidimentional int array with the following function code:
int ** createIntMatrix(unsigned int rows, unsigned int cols)
{
int ** matrix;
unsigned int i,j;
matrix = (int **) calloc(cols, sizeof(int *));
for(i = 0; i < cols; i++)
matrix[i] = (int *) calloc(rows, sizeof(int));
for(i = 0; i < cols; i++)
for(j = 0; j < rows; j++)
matrix[i][j] = 0;
return matrix;
}
I create three instances using this function in the following code,
cout<<"allocating temporary data holders..."<<endl;
int ** temp_meanR;
int ** temp_meanG;
int ** temp_meanB;
temp_meanR = createIntMatrix(img->height,img->width);
temp_meanG = createIntMatrix(img->height,img->width);
temp_meanB = createIntMatrix(img->height,img->width);
cout<<"....done!"<<endl;
I’m accessing these elements like temp_meanB[4][5].
But unfortunately, I get the following error during runtime:
allocating temporary data holders...
....done!
tp6(1868) malloc: *** error for object 0x122852e08: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Abort trap
Where am I going wrong here?
note the inside for loop, it says
j=0; i<rows; i++(before Aarohi Johal’s edit)Next you do not have to set the memory manually to 0, as
callocdoes it for you.In C++, you should use
newanddelete.In the code segment
I think first the rows should be allocated and then for each row link the
intarrays.Visulize like this:
First do the rows and then the cols, in the above visualization, then the
arr[i][j]interpretation would be like normal array.