2

I've just write a code to free a multidimensional tab of float:

void matrix_destroy(float **that)
{
        for (int y = 0; y < 3; ++y) {
            for (int x = 0; x < 3; ++x) {
                free (that[y][x]);
            }
        }
        free (that);
}

And I got that error that I don't understand... :

SRC/creators_destructors.c: In function ‘matrix_destroy’: SRC/creators_destructors.c:56:10: error: incompatible type for argument 1 of ‘free’
free (that[y][x]);
      ^~~~ In file included from ./include/mylibs.h:13:0,
             from SRC/creators_destructors.c:8: /usr/include/stdlib.h:448:13: note: expected ‘void *’ but argument is of type ‘float’  extern void free (void *__ptr) __THROW;
         ^~~~
# cc1 0.01 0.00
make: *** [<builtin>: SRC/creators_destructors.o] Error 1

If someone can help me

My code to it is as follow:

float **my_matrix;

    if ((my_matrix = malloc(sizeof(float *) * 3)) == NULL)
        perror("");
    for (int i = 0; i < 3; ++i) {
        if ((my_matrix[i] = malloc(sizeof(float) * 3)) == NULL)
            perror("");
    }
    for (int y = 0; y < 3; ++y) {
        for (int x = 0; x < 3; ++x) {
            if (x == 0 && y == 0)
                my_matrix[y][x] = 1;
            else if (x == 1 && y == 1)
                my_matrix[y][x] = 1;
            else if (x == 2 && y == 2)
                my_matrix[y][x] = 1;
            else
            my_matrix[y][x] = 0;
        }
    }
    return (my_matrix);

2 Answers2

5

You're trying to free each individual float instead of the allocated pointers.

Assuming you've allocated the matrix doing something like this:

float **that = malloc(3 * sizeof *that);
for (int i = 0; i < 3; i++) {
    that[i] = malloc(3 * sizeof **that);
}

Then you need to free each inner pointer and then the outer pointer, like this:

for (int i = 0; i < 3; i++) {
    free(that[i]);
}

free(that);
Mac O'Brien
  • 2,407
  • 18
  • 22
2

On this line:

free (that[y][x]);

You're not passing a pointer to free. You're passing a float. The variable that has type float **, so that[y] has type float * and that[y][x] has type float.

Looking at your allocation code, you to a single malloc for an array of pointers, then a single loop to malloc one or more arrays of float. So you deallocation should do the same in the reverse order:

for (int y = 0; y < 3; ++y) {
    free (that[y]);
}
free (that);

As a rule, the code for freeing should mirror the cold that's allocating.

dbush
  • 205,898
  • 23
  • 218
  • 273