I always have this doubt in mind. Please see the below program:
#include <stdio.h>
char * function1(void);
int main()
{
char *ch;
ch = function1();
printf("hello");
free(ch);
return 0;
}
char* function1()
{
char *temp;
temp = (char *)malloc(sizeof(char)*10);
return temp;
}
am i leaking the memory here?
the program does not crash in ideone with some warnings:
prog.c: In function ‘main’:
prog.c:11: warning: implicit declaration of function ‘free’
prog.c:11: warning: incompatible implicit declaration of built-in function ‘free’
prog.c: In function ‘function1’:
prog.c:19: warning: implicit declaration of function ‘malloc’
prog.c:19: warning: incompatible implicit declaration of built-in function ‘malloc’
and prints hello.
I am just a beginner in C.so please help me understand what happens after the return statement in function1.does free really frees the memory allocated in funtion1?
Memory leaking
You are code isn’t leaking any memory because you do
free(ch);whichfree‘s memory allocated by themallocinside thefunction1function.You can check this by printing the pointer addresses, i.e.:
and
You should see that both prints (
chandtemp) will print the same address. Thus,free(ch);willfreethe correctmalloced chunk of memory.You can use valgrind too check if your code doesn’t
freeallocated memory.About the warnings
Functions
free,mallocare defined atstdlib.h.Add this in your code:
Also, it’s not such a good idea to cast
mallocreturn valuetemp=(char *)malloc(...);.Have a read here.