Hi!
I am trying to explore skills in C, however, I think I don't have a very good background in topics such as malloc.
I am trying to convert multiple images (.bmp) into two-dimensional arrays for image processing. Importing the image and processing it one-by-one in a for-loop. I'm having trouble with managing the memory usage and the program crashes because i think it's taking so much memory. I wish to assign same memory over and over in the for-loop.
I think the problem is on how I use the malloc and the free for my two-dimensional array.
Please check if I'm using them correctly for my two-dimensional array.
Code:
int **image_matrix;
//Allocate memory and initialize image_matrix
image_matrix = (int **)malloc(rows * sizeof(int *));
if (NULL == image_matrix)
{
free(image_matrix);
printf("Memory allocation failed while allocating for the array[].\n");
exit(1);
}
image_matrix[0] = (int *)malloc(cols * rows * sizeof(int));
for(r=1; r<rows; r++)
{
image_matrix[r] = image_matrix[0] + r*cols;
}
for(r=0; r<rows; r++)
{
for(c=0; c<cols; c++)
{
image_matrix[r][c] = 0;
}
}
//Free image_matrix
for(r=1; r<rows; r++)
{
free(image_matrix[r]);
}
free(image_matrix);