Reputation: 33
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);
Upvotes: 3
Views: 5021
Reputation: 1799
If you want to check that the memory is freed, you should use the Valgrind
program.
See The Valgrind Quick Start Guide
In this case, try this:
free(matrix[0]);
free(matrix);
Upvotes: 0
Reputation: 34626
You have two malloc
s, so you need two free
s. But you can optimise a bit if you rearrange your allocation:
/...
void* mcontent;
if (!(mcontent = malloc(height*sizeof(char*) + height*width*u_size))) {
printf("Memory allocation error.\n");
exit(0);
}
array = (char **)mcontent;
array[0]=(char *)(mcontent + height*sizeof(char*));
This has two advantages. First, usability: you only have to free your matrix "object" without bothering how it was made. Second, efficiency: you have locality AND only one allocation, which both means speed.
Upvotes: 2
Reputation: 11162
If you like, you can use the beautiful C99 pointer-to-variable-length-array.
Allocate like this:
char (*arr)[width] = emalloc(width*height);
Index like this:
arr[23][10] = 2; //row 23, column 10
And free like this:
free(arr);
Upvotes: 1
Reputation: 399863
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()
.
Upvotes: 5