If it does it’s by accident, maybe you are overwriting an area which you never return to anyway, since you exit() the program. I think that if you try that strcpy() in a function you may get a different result.
The point is that you cannot rely on it working correctly because you have a program error. The behaviour is indeterminate.
I agree with ken_yap and only want to cite the man page (bugs section) from strcpy to point out that this is not the right usage of strcpy:
If the destination string of a strcpy() is not large enough (that is, if the programmer was stupid or lazy, and failed to check the size before copying) then anything might happen. Overflowing fixed length strings is a favorite cracker technique.
> If it does it’s by accident, maybe you are overwriting an area which you
> never return to anyway, since you exit() the program. I think that if
> you try that strcpy() in a function you may get a different result.
> The point is that you cannot rely on it working correctly because you
> have a program error. The behaviour is indeterminate.
Well Ken I know that it works by accident and it is the accident that I want
to understand. Guide me.
I already proposed a likely explanation. You don’t use the area of the stack that you have destroyed because you are calling exit(). If you were to put that strcpy in a function, it would probably crash on the return from the function. Also the area of the stack above the stack pointer is finite. If you use longer strings, eventually at some point you will try to overwrite an area which is outside of your program’s area and cause an exception which will make the OS terminate your program on the spot.
If you wish to understand such pathologies you have to study how C code is turned into machine code and what the layout of machine memory looks like and how the machine’s registers are used. Otherwise if you just want reliable programs, avoid such errors.