Search code examples
cmemorydynamicfree

Deallocate contiguous block of memory for a 2D array


I understand I'm splitting the array over the double pointer, but how can I deallocate if I lost the data track?

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

#define width 20
#define height 20

void allocate_matrix(int ***matrix)
{
    double **local_matrix, *data;
    local_matrix = (double **)malloc(sizeof(double *) * height);
    data = (double *)malloc(sizeof(double) * width * height);
    for (int i = 0; i < height; i++)
    {
        local_matrix[i] = &(data[i * width]);
    }
    *matrix = local_matrix;
}

void deallocate_matrix(int **matrix) {
    
}

int main(void) {
    int **matrix;
    allocate_matrix(&matrix);
    deallocate_matrix(matrix);
    return 0;
}

Solution

  • You didn't lose track of the second pointer. If you look at your loop body:

    local_matrix[i] = &(data[i * width]);
    

    When i is 0, local_matrix[0] is assigned &data[0] which is the same as data. So that's what you need to free:

    void deallocate_matrix(int **matrix) {
        free(matrix[0]);
        free(matrix);
    }