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.
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.
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.
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].
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.
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...
That's undefined behavior - once you've free
d 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With