shibly shibly - 1 month ago 17
C Question

How can I free memory?

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

int * doall() {
int *a;
a=(int*)malloc(sizeof(int)*2);
a[0]=2;
a[1]=3;
return a;
}
int main() {
int *arr;
arr=doall();
for(int i=0;i<2;i++) {
printf("%d ",arr[i]);
}
printf("\n");
free(arr);
return 0;
}


Is it possible to
free(a);
? Does
free(arr)
deallocate "a" in
doall
function?

In
doall
a=(int*)malloc(sizeof(int)*2);

Answer

Is it possible to free(a);

No. By the time doall finishes, there's no variable a, only its value. However, since this value is then assigned to arr, your program retains the reference to the block that doall has allocated.

Does free(arr) deallocate a in doall function?

It does not deallocate a because at the time free is called variable a is already gone. However, it deallocates memory that has been previously assigned to a, so there is no memory leak.

Comments