I know that an invalid pointer leads to undefined behaviour but how does free know whether a pointer is valid or not?
Is there kind of a checksum at the beginning of each block in free list?
something like:
if((*ptr) == 'CHECKSUM'))
free
else
do something undefined
The only check is whether the pointer is null or not. If it’s a null pointer, free (by specification) will do nothing.
Otherwise,
freejust tries to “free” the memory, making the assumption that it was memory allocated bymalloc,calloc, orrealloc, which can make anything happen (typically bad things) – hence “undefined behavior.”