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 result obtained is as follows:
[root@lnxdesk Tazim]# ./a.out 154804232 154804232 154804232
Why is this address inside p still printing, even if I did free(p);? What did free(p)you do ?
free(p);
free(p)
I want to clearly understand the concept of free / malloc. Any help would be helpful.
free()only frees memory on the heap. It does not change the value of your pointer. If you tried to print the memory indicated by your pointer, you might get some kind of garbage.
free()
In addition, when you called free, you pointed the pointer to it, not the address of the pointer, so freeyou cannot change the pointer ...
free
undefined - , free d , , , - , printf() .
printf()
, .. , . free 0x00, , .
, .
*p free(p), .
*p
malloc() , "", . , p , , , ( 154804232). *p = 10, 10 . q = p, q, .
malloc()
p
*p = 10
10
q = p
q
free(), ilk . free(), : " ". free() , . . . , .
, . . . . , , , - , , , - . , Bad Things Happen <tm> . , .
: - , . , malloc, , . , malloc(), - . , - ( , , "" ). NULL , ; , - .
, - . , C . , :
A free function causes a space pointed to by ptr, which should be freed, i.e. available for further distribution. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match the pointer previously returned by calloc, malloc, or realloc, or if the space was freed by a call to free or reallocate, the behavior is undefined