to learn Heap memory, I used the following code. I used malloc inside a called function (fn1), and for some I reason, I decided not to free the memory inside the called function (fn1). I passed the address of the random alocated memory as return to the calling function(fn2). So after using the data from the heap memory in called function(fn2), can I free the malloc memory outside the called function(fn1)?
#include <stdio.h>
#include <stdlib.h>
int *add ( int*a, int*b)
{
int *c = (int*)malloc(sizeof(int));
*c = (*a)+(*b);
return c;
}
void main()
{
int a=2, b=3;
int *s = add(&a,&b);
printf("The sum is: %d\n", *s);
free(s);
}
In the above code, I'm returning the dynamically allocated value c as function return and storing it in s. Will free(s); clear the space in heap memory?