#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
int * ptr;
printf("before malloc pointer is :%p \n",ptr);
printf("before malloc valu is :%d \n",*ptr);
ptr = malloc(sizeof(int));
printf("after malloc pointer is %p \n",ptr);
printf("after malloc valu is :%d \n",*ptr);
int jig=32;
*ptr = jig;
printf("after assignment valu is : %d\n",*ptr);
free(ptr);
printf("after free %p \n",ptr); // after free pointer holds sane address then
printf("after fee is %d\n",*ptr); // why it coudnt print that???
return 0;
}
output is :
before malloc pointer is :0x6edff4
before malloc valu is :7265660
after malloc pointer is 0x9a52008
after malloc valu is :0
after assignment valu is : 32
after free 0x9a52008
after fee is 0
after free still pointer holds the address of that memory then why we can not print that memory’s value.??
what does free() do.?
does it just make all memory as 0 ..??
Because the memory no longer belongs to you. You
freed it, which means the OS is allowed to reuse it however it sees fit, wherever it needs to allocate more memory. You no longer own it, therefore you no longer have any business looking at the value of the data held by that memory.Note also that:
is equally invalid.
ptrholds a garbage value, and can point anywhere. Dereferencing it is not guaranteed to be a memory location you can access.Both of these cases invoke undefined behavior, which means the standard says, "DON’T DO THIS," and if you ignore the standard your code will break in horrible ways whenever your boss is looking.
No, not necessarily. The OS often zeroes out unused memory in the background to make calls to
callocfaster, butfreeonly tells the operating system "I’m done with this memory, do whatever you need to with it." The OS typically updates some housekeeping data to indicate that the block of memory is no longer owned by a process, so that a later call tomalloccan use it if it’s needed.