The real reason is most likely that you're just overwriting the contents of your stack since you're in a function call, and you don't actually get to memory you don't own until you to try to write characters past the bottom of it. Even though it doesn't crash, this is almost always bad because you're overwriting values that your program put there for a reason. After all, if you always crashed every time you overwrote a buffer, then buffer overflow bugs could never occur, and we know they do.
For instance, your stack is likely growing downwards. When you make a function call, you might get register values, a return address, argument values, and other things placed onto the stack. Then, and only then, will your 6 bytes for buf
be allocated. If all that other stuff took up, say, 12 bytes, then you could write 18 characters to buf
and still be only touching memory that you shouldn't be changing, but that your process owns. Since your process owns it, you won't get an illegal memory access, and you won't crash. Once you go past the 18 bytes, then you may very well get into memory that your process doesn't own, and you'll get a segfault and the game will be up.
The C reason is that you just have undefined behavior and weird stuff happens that you shouldn't even try to understand.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…