0

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);
}

1 Answers1

-3

Try this

#include <stdio.h>
#include <stdlib.h>

float **create_matrix(int h, int w)
{
    float **matrix = (float **)malloc(h*sizeof(float *));
    int i,j;
    for(i=0;i<h;i++){
       matrix[i] = (float *)malloc(w*sizeof(float));
    }
    for(i=0;i<h;i++){
        for(j=0;j<w;j++){
            matrix[i][j] = (i+1)*(j+1);
        }
    }
    return matrix;
}

int main()
{
    int h = 2, w = 3;
    float **matrix = create_matrix(h,w);
    int i,j;
    for(i=0;i<h;i++){
        for(j=0;j<w;j++){
            printf("%.2f ",matrix[i][j]);
        }
        printf("\n");
    }
    return 0;
}

You need to allocate memory before you start making operations.

Atul Shanbhag
  • 636
  • 5
  • 13