1

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;         
}
  • You don't need to free the array in this case because the allocations are not repeated and the OS will free the memory after the execution ends. For more information, see [c - What REALLY happens when you don't free after malloc? - Stack Overflow](https://stackoverflow.com/questions/654754/what-really-happens-when-you-dont-free-after-malloc) – MikeCAT Nov 22 '20 at 00:01
  • If you have to free memory (long-running process that might conceivably starve), then the rule is "Free whatever you malloc". – Mark Benningfield Nov 22 '20 at 00:13
  • Does this answer your question? [How to free 2d array in C?](https://stackoverflow.com/questions/5666214/how-to-free-2d-array-in-c) – Krishna Kanth Yenumula Nov 22 '20 at 05:33

3 Answers3

1

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);
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • thank you so much!! and what about the loop arr[i]? i need to run it or just write free(arr)? – daniel evanenko Nov 22 '20 at 00:16
  • @danielevanenko The loop is required if you want to manually free everything you allocated. Practically no `free()` here are required because the memory used will be freed by the OS after exiting of the process. – MikeCAT Nov 22 '20 at 00:20
1

**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).

0

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___________
  • 60,014
  • 4
  • 34
  • 74