Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

free() 2D Arrays in C Using malloc

I would like to use free() to remove the whole matrix arrays from memory. How can i do it?

Allocate arrays:

// test.h
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

#define BYTE unsigned char
#define  my_array(n_height, n_width) (BYTE **)create_array(sizeof(BYTE), (n_height), (n_width))

char  **create_array(int u_size, int height, int width);
char  **create_array(int u_size, int height, int width)
{
    char  **array;
    int     i;

    if (!(array=(char **)malloc(height*sizeof(char *)))) {
        printf("Memory allocation error.\n");
        exit(0);
    }
    if (!(array[0]=(char *)malloc(height*width*u_size))) {
        printf("Memory allocation error.\n");
        exit(0);
    }
    for (i=1; i<height; i++)
        array[i] = array[i-1] + width*u_size;
    return array;
}

// test.c
#include "array.h"
int main()
{
    unsigned char *bytes;
    BYTE  **matrix;
    matrix = my_array(height, width);

    int c = 0;
    for (int h=0; h < height; h++) {
        for (int w=0; w < (width); w++) {
            matrix[h][w] = bytes[c];
            c++;
        }
    }

    printf("Done.\n");

    free(matrix); // really empty memory??
}

I am not sure whether matrix has been completely removed from the memory when i use free(matrix);

like image 803
wowofe Avatar asked May 22 '26 19:05

wowofe


1 Answers

You must call free() exactly once per call to malloc(). You can't "fool" free() into free:ing several blocks. If you want to be able to call free() only once, you'll need to make sure to allocate all the required memory in a single call to malloc().

like image 198
unwind Avatar answered May 24 '26 13:05

unwind