Question

Given the following code written in C:

#include<stdio.h>
#include<stdlib.h>

typedef struct {
    int var;
    int **m;
} STRUCTURE;

int main() {
    STRUCTURE a;
    int i, j;

    a.var = 5;

    a.m = malloc(a.var * sizeof(int *));
    for(i = 0; i < a.var; i++) {
        a.m[i] = calloc(a.var, sizeof(int));
    }

    for(i = 0; i < a.var; i++) {
        a.m[i][i] = 1;
    }

    for(i = 0; i < a.var; i++) {
        for(j = 0; j < a.var; j++) {
            printf("%d ", a.m[i][j]);   
        }
        printf("\n");
    }

    return 0;
}

Which will simply output:

1 0 0 0 0 
0 1 0 0 0 
0 0 1 0 0 
0 0 0 1 0 
0 0 0 0 1 

Given the fact that the structure was declared in main, but pointers from it were allocated dynamically, how should they be freed? If they should.

Thank you!

Was it helpful?

Solution

Anything you malloced must be freed as well. An exception would be when exiting, as usually the OS will claim the memory anyway (depends on the OS). Still it would be considered bad practice, even though it technically wouldn't be a memory leak.

The free should be done in the reverse order to what you usedin to allocate.

for(i = 0; i < a.var; i++) {
    free(a.m[i]);
free(a.m);

Reason is, that you can not free the main body before you freed the pointers inside it, as they are not accessible anymore.

OTHER TIPS

free() just works the same way as malloc, though you normally want it in the opposite order. You should use something like something like:

for(i = 0; i < a.var; i++) {
    free (a.m[i]);
}
free (a.m);

In reverse

for(i = 0; i < a.var; i++) {
    free(a.m[i]);
}
free(a.m);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top