Search code examples
cfreecalloc

How should I free an array in C?


I created a function to free an array in C, but I don't know whether it is correct or not:

void dealloc_array(void *array[], int size) {

         int i = 0;

         for (i = 0; i < size; i++) {

                if (array[i]) free(array[i]);
         }

         if (array) free(array);


}

I'm not sure whether I should execute free(array) at the end. Technically, we've already freed all the array elements, so we don't need to do free(array).

Thanks for the help.


Solution

  • If you malloc the pointer as well as each element of the array you will need to free that pointer after your for loop.

    For example:

    int **array;
    array = malloc(SIZE*sizeof(int*));
    for(int ii = 0; ii < SIZE; ii++)
    {
         array[ii] = (int*)malloc(sizeof(int));
    }
    

    you will have to free each element and free array. Essentially for every malloc/calloc you have, you must have a free