The C standard description of
free says the following:
freefunction causes the space pointed to by
ptrto be deallocated, that is, made available for further allocation.
If ptris a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
Since you changed the pointer, it does not match a pointer returned by a memory management function (i.e.
m/re/calloc), the behaviour is undefined, and anything can happen. Including the runtime library noticing that you’ve tried to free an invalid pointer, but the runtime is not required to do that either.
- Does C keep track of memory’s allocated on the heap
It might… but it does not necessarily have to…
- If not, how does it know what to free and what to not?
Well, if it does free the memory pointed to by a pointer, then it obviously need to have some kind of bookkeeping about the sizes of the allocations… but it does not need to be able to figure out if any pointers are still pointing to that memory area.
- And if it has such a knowledge, why doesn’t c automatically deallocate such memories just before exiting. why memory leaks?
Usually memory is freed after the process exits by the operating system. That’s not the problem. The real problem are the leaks that happen while the program is still running.
CLICK HERE to find out more related problems solutions.