I am a newbie when it comes to dynamic memory allocation. When we free the memory using void free(void *ptr) the memory is deallocated but the contents of the pointer are not deleted. Why is that? Is there any difference in more recent C compilers?
I am a newbie when it comes to dynamic memory allocation. When we free
Share
Computers don’t “delete” memory as such, they just stop using all references to that memory cell and forget that anything of value is stored there. For example:
Once the function has finished, the program stops reserving the memory location where
xis stored, any other part of the program (or perhaps another program) is free to use it. So the above code could print 5, or it could print garbage, or it could even crash the program: referencing the contents of a memory cell that has ceased to be valid is undefined behavior.Dynamic memory is no exception to this and works in the same manner. Once you have called
free(), the contents of that part of the memory can be used by anyone.Also, see this question.