Let’s say we have:
void createMultiArray(){
int i,j;
char*** codes = malloc(5 * sizeof(char**));
for ( i = 0; i <= 4; i++ ) {
codes[i] = malloc((i+1) * sizeof(char*));
for ( j = 0; j <= i; j++ ) {
codes[i][j] = malloc(2 * sizeof(char));
}
}
How should I free codes?
free(codes);
or
int i,j;
for(i = 0; i <=4; i++){
for(j = 0; j <= i; j++){
free(codes[i][j]);
}
free(codes[i]);
}
free(codes);
Think about it this way – you should have a
freefor everymalloc.So yes, your second option is the correct one.