Dear All,
I am trying to use free function in C to free memory of an array of pointers. It does not work and I get segmentation fault. The code looks like this:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *make_pointer(int);
void read_array(int *array[3]);
/****************/
int *array[3] ;
array[0] = make_pointer(1);
array[1] = make_pointer(2);
array[2] = make_pointer(3);
/****************/
read_array( array );
/****************/
/** !! The problem is here !! **/
free(array);
return 0;
}
/******************************/
int *make_pointer(int i){
int *x;
x = malloc(sizeof(int));
*x = i;
return x;
}
/******************************/
void read_array(int *array[3]){
int i;
/****************/
for (i=0; i< 3; i++) {
printf("The value of %d= %d \n", i, *array[i]);
}
}
However it works when I write
free(array[0]);
free(array[1]);
free(array[2]);
But this does not look like a clever solution!
Would you have a better idea?
Thanks in advance!