Below I am using function input to collect and return a string to function main. I stored the returned pointer/string in a char* and am using that variable to free the malloced memory after using it.
However, it appears that the malloced memory is still usable after my free call.
char* input();
const int MAX = 100;
int main() {
while(1) {
char * input_function_pointer = input();
printf("%p", &input_function_pointer);
puts(input_function_pointer);
free(input_function_pointer);
puts("_______");
printf("%p", &input_function_pointer);
puts(input_function_pointer);
puts("_______");
}
return 0;
}
char* input() {
char * str = malloc(MAX);
printf( "Enter a value :");
fgets( str, MAX, stdin );
return str;
}
Freeing memory does not enforce erasing its content (depends on compiler option, mostly debugging turned on) and nothing prevents you from accessing that space. You're in Undefined Behavior accessing what is called a "dangling pointer": you will probably still see the same content right after you've freed it, probably not after other malloc are called ... or crash.
Freeing memory is merely marking that space as available for allocation, not preventing further read (or write) access. That's (also) why C is considered "low level".