How does malloc(sizeof(char)) work
Quick note, sizeof(char) is defined to be 1. So you can just simplify to malloc(1).

The real answer however is quite boring. Your program has what's so called undefined behavior. In C (and C++), if you make an error like this the result is undefined. This could mean that your program will crash right as you trigger the bug. But it doesn't necessarily crash. It might do what you expect. It might format your hard drive and kill your cat. Whatever happens is fair game according to the C standard. Because you triggered undefined behavior.