I wanted to know what happens in this piece of code?
Here, I have a variable f2 in func2 where it is allotted a block of space via malloc and a variable f1 in func1 which is also allotted a block of space via malloc.
#include <stdio.h>
#include <stdlib.h>
char* func2(){
char *f2 = (char *)malloc (sizeof(char) * 10);
f2[0] = '1';
f2[1] = '2';
f2[2] = '3';
f2[3] = '\0';
return f2;
}
char* func1(){
char *f1 = (char *)malloc (sizeof(char) * 10);
f1 = func2();
return f1;
}
int main()
{
printf("String: %s", func1());
return 0;
}
Now, since I have allotted a heap memory in func2, and func1 is calling it, then func1 should free that memory. But I am allocating the returned value to one of func1's local variable f1 and would return that variable to main function I can't delete it in func1.
So, how will I free the memory that was allocated in func2.
Is the heap memory space for f1 in func1 and f2 in func2 the same?