Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding concept of free

Tried the following code :

#include<stdio.h>
int main()
{        
        int *p,*q;
        p = (int *)malloc(sizeof(int));
        *p =10;
        q = p;
        printf("%u \n",p);
        printf("%u \n",q);
        free(p);
        printf("%u \n",p);
        return 0;
}

The output got is as follows :

[root@lnxdesk Tazim]# ./a.out
154804232
154804232
154804232

Why is that address inside p is still printed even if I have done free(p);? What has free(p) done then?

I want to understand the concept of free/malloc clearly. Any help will be valuable.

like image 859
Star123 Avatar asked Mar 21 '11 12:03

Star123


People also ask

What is the concept of free?

exempt from external authority, interference, restriction, etc., as a person or one's will, thought, choice, action, etc.; independent; unrestricted. able to do something at will; at liberty: free to choose.

What are the main concepts of free will?

free will, in philosophy and science, the supposed power or capacity of humans to make decisions or perform actions independently of any prior event or state of the universe.

Why is understanding free will important?

Free will is largely considered as a necessary condition for moral responsibility. O'Connor and Franklin note (with many references to literature) that “the kind of control or sense of up-to-meness involved in free will is the kind of control or sense of up-to-meness relevant to moral responsibility” [16].

What is the meaning of free in philosophy?

1) The absence of human coercion or restraint preventing one from choosing the alternatives one would wish. 2) The absence of physical constraints in natural conditions which prevent one from achieving one's chosen objectives.


3 Answers

free() only frees the memory on the heap. It does not change the value of your pointer. If you tried to print the memory pointed by your pointer, you'll probably get some kind of garbage.

Also, when you called free, you gave it the pointer, not the address to your pointer, so free can't change your pointer...

like image 73
MByD Avatar answered Oct 12 '22 16:10

MByD


That's undefined behavior - once you've freed the pointer the address stored becomes invalid and you can't do anything with it - not only you can't dereference it, but you can't even printf() the pointer value.

like image 45
sharptooth Avatar answered Oct 12 '22 16:10

sharptooth


You are printing the pointers, i.e. the address of the memory zones allocated for you ints. Freeing a memory zone with free does not set the pointer's address to 0x00 as I think you expect.

It just tells the OS that the memory zone is available again for future re-use.

If you were printing *p after free(p), you would have problems.

like image 2
Sylvain Avatar answered Oct 12 '22 16:10

Sylvain