Skip to main content
2 of 2
Commonmark migration

after free still pointer holds the address of that memory then why we can not print that memory's value.??

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:

int *ptr;
...
printf("Before malloc valu is :%d\n", *ptr);

is equally invalid. ptr holds 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.

what does free() do.?

does it just make all memory as 0 ..??

No, not necessarily. The OS often zeroes out unused memory in the background to make calls to calloc faster, but free only 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 to malloc can use it if it's needed.

Chris Lutz
  • 76.1k
  • 16
  • 134
  • 184