Two things to know:
- You have two area in you memory (to make easy t understand) heap and stack
- malloc, realloc, calloc allocate ressource from heap. I will say only malloc (but it is the same)
- free can only free ressource from heap. Stack is reserver for the compiler (it store function call and other data)
The rule for each ressource you get from malloc you have to free it.
to free simply call the free function (but we can optionally assigne null pointer to be sure it is freed).
char * a = malloc(255);
to free
free(a);/* this is mandatory */
a = NULL;/* we can add this to the first line */
In fact it you take the habit to assign NULL value and one time you access it's value you will have NULL deference error: so you will know where to find error
What you try to do:
alloc a array char ** arr = malloc(nrows * sizeof(char *));
and you free it free(arr);
but you alloc 20 arrays of char arr[i] = malloc(ncolumns * sizeof(char));
you ignore it's value arr[0] = "string1";
(you loose the value returned by malloc so you can't free now arr[0]) we are not in C++. So "string1" is stocked on the stack (so malloc can't free it)
and you call free on it.
what you can do
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int nrows = 20; int ncolumns = 10;
char ** arr = malloc(nrows * sizeof(char *));
for(int i = 0; i < nrows; i++)
arr[i] = malloc(ncolumns * sizeof(char));
free(arr[0]);//know we can loose it value because it is freed
arr[0] = NULL;// in fact we assign a value just after so this line is useless but is educationnal purpose
free(arr[1]);//know we can loose it value because it is freed
arr[1] = NULL;// in fact we assign a value just after so this line is useless but is educationnal purpose
arr[0] = "string1";
arr[1] = "string2";
// does not work without the following code:
// for(int i = 0; i < 20; i++)
// arr[i] = NULL;
for(int i = 2; i < 20; i++)//we start at 2 because the first two value are on the stack
{
free(arr[i]);
arr[i] = NULL;//this is useless because we will free arr just after the loop)
}
free(arr);
arr = NULL;// this is useless because we exit the end of program
return 0;
}