It doesn't seem like it should work, but when I output everything, it looks right.
Welcome to the world of Undefined Behavior. When you do this, anything can happen. Your program may crash, your computer may crash, your computer may explode, demons may fly from your nose .
And worst of all, your program can work just fine, imperceptibly looking as if it is working correctly, until one fine day it begins to spill garbage, because it is rewriting confidential data somewhere because somewhere someone allocated too few characters for their arrays, and now you messed up the heap and you get segfault at some point for a million miles, or worse, your program will happily combine with the damaged heap and your functions will work on the damaged numbers credit cards and you by radiate huge misfortune.
Even if it looks like it works, it is not. This is Undefined Behavior. Avoid this, because you can never be sure what he will do, and even when what he does, when you try, everything is in order, on another platform it may not be so.
source share