How do I free 2D array allocated with malloc?

107 Views Asked by At

How do I free this array? Is this enough? Would it be enough to write only free(arr)? Do I need to free **arr? If yes, how can I do that? Thanks in advance!

#include <stdio.h>
#include<stdlib.h>
#define N 5
int main(void)
{
    int **arr = malloc(N*sizeof(int*));

    for(int i=0;i<N;i++)
    {
        arr[i] = malloc(N*sizeof(int));
    }
    for(int i=0;i<N;i++)
        free(arr[i]);
    free(**arr);

    return 0;         
}
3

There are 3 best solutions below

2
On

You don't need to free **arr because **arr is an int.

Instead of that, you should free the allocated pointer arr.

The line

    free(**arr);

should be

    free(arr);
0
On

if you want to declare two-dimensional array instead of the array of pointers (and I think that is your idea)

int foo(size_t x, size_t y)
{
    int (*arr)[x][y];

    arr = malloc(sizeof(*arr));

    (*arr)[4][2] = 5;

    free(arr);


}

You can index it as any other array and you need only one free

0
On

**arr in this case is equivalent to arr[0][0], which is actually an integer, and free function expects a pointer to memory. So free(**arr) would be "freeing" an integer pretending to be a pointer in memory, and that would cause your program to crash.

What you need to do is free a pointer to array of 5 pointers, and this pointer is simply arr. So you need to free(arr).