-2

I allocated memory for pointer using malloc function. I had deallocate memory using free. But whenever I'm trying to print the content of pointer it prints the content.

Then what is the use of free()?

Abhishek Anand
  • 1,940
  • 14
  • 27
saipriya
  • 11
  • 2
  • 3
  • 4
    `free()` just marks the memory as available (as in, it can be used for further allocations). It does not removes the content of the memory. But, you should not access the content of a `free`d memory, as it is Undefined Behaviour. – Haris Mar 29 '16 at 16:08
  • think! What would you expect the pointer to do? Try doing some more malloc's and then print the "content" and see what's there. Good practice is to set value of pointer to null after you free it. – CarlH Mar 29 '16 at 16:13

1 Answers1

1

free() just marks the memory as available (as in, it can be used for further allocations). It does not removes the content of the memory.

That said, you should not access the content of a freed memory, as it is Undefined Behavior.

Haris
  • 12,120
  • 6
  • 43
  • 70
  • 1
    Just to add on to this, because you've freed something, you should also set that pointer to null to prevent any dangling pointers hanging around – Tmayto Mar 29 '16 at 16:12
  • If that is such a good idea, I wonder why free() does not take a pointer-to-pointer argument so that it can, itself, set the pointer to NULL? – Martin James Mar 29 '16 at 16:47