I have this code for allocating a float matrix on runtime:
float **create_matrix(int w, int h) {
// alocates the matrix rows first
float **matrix = (float**)malloc(h * sizeof(float*));
// now allocates and populates each line
for (int i = 0; i < h; i++) {
matrix[i] = (float*) malloc(w * sizeof(float));
// sample matrix filling
for (int j = 0; j < w; j++)
matrix[i][j] = (i + 1) * (j + 1);
}
return matrix;
}
It seems to be working fine, since it doesn't crash and when I display the matrix I have the very same values that I initialized it. Although when I try to free the matrix, iff the number of rows is lesser than the number of columns, I receive the following error message:
a.out(14284,0x7fff73cc9300) malloc: * error for object 0x9000000000000000: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug. Abort trap: 6"
My freeing routine follows:
void free_matrix(float **matrix, int h) {
for (int i = 0; i < h; i++)
free(matrix[i]);
free(matrix);
}