How does free() 'know' that passed pointer is valid?

c, free, pointers

Solution

I know that an invalid pointer leads to undefined behaviour but how does free know whether a pointer is valid or not?

The only check is whether the pointer is null or not. If it's a null pointer, free (by specification) will do nothing.

Otherwise, `free` just tries to "free" the memory, making the assumption that it was memory allocated by `malloc`, `calloc`, or `realloc`, which can make anything happen (typically bad things) - hence "undefined behavior."

Problem

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 ```

Original source

Related problems