seamus
seamus

Reputation: 2901

Malloc'ed memory returned by function is not being freed

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;
}

Upvotes: 0

Views: 102

Answers (4)

0___________
0___________

Reputation: 67476

free does not amend the content of the freed memory. It does not also change the pointer.

The pointer containing the reference to the freed memory is called dangling pointer and dereferencing it (as you do in your program) is an Undefined Behaviour

Upvotes: 1

Matthieu
Matthieu

Reputation: 3098

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".

Upvotes: 3

Tony Tannous
Tony Tannous

Reputation: 14866

7.22.3.3 The free function c11

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation

Dereferencing dangling pointer invokes undefined behavior.

Upvotes: 2

Mureinik
Mureinik

Reputation: 311163

There are no guarantees what will happen if you try to access a chunk of memory after freeing it. This is undefined behavior, which just happens to work in this case, with your specific compiler.

Upvotes: 2

Related Questions