Fundamentally, accessing pointer[-1]
the way you did yields Undefined Behavior; in theory, anything could happen. But in practice, there’s a good explanation for the particular error message you got.
Recall that malloc
has to save the size of the allocated chunk of memory somewhere so that free
can work correctly. On some systems — and it seems yours is among that bunch — this information is stored in memory just before the address that malloc
returns. (It might be interesting to print out that value, if you want to learn about your system’s implementation.)
When you overwrote that chunk of memory, you left the internals of the malloc
-free
system in an inconsistent state, leading free
to report an error when this was discovered. The most likely time for such a discovery, of course, is when the memory management functions are called about this area of memory. (Some malloc
corruptions will be detected the next time you call malloc
, but that usually takes more deliberate effort to achieve.) Calling realloc
should give you a similar error message.