Before strcpy
:
name2 [ ] [ ] [ ] [ ] [ ]
name [T] [h] [e] [ ] [B] [a] [t] [m] [a] [n] [\0]
After strcpy
:
name2 [T] [h] [e] [ ] [B]
name [a] [t] [m] [a] [n] [\0] [t] [m] [a] [n] [\0]
i.e. the strcpy
overrun the memory allocated by name2
onto the start of name
rewriting the contents at the start.
Of course, when you print name
, the print will stop at \0
and will only show "atman".
When you print name2
it will exceed the 5 characters you assigned and overrun into name
memory and show you (what you believe is correct) "The Batman"
, but, it is already indicating something is wrong in that you can see a string stored there that's larger than the memory you allocated.
You are lucky your programming didn't crash.
The code that you provided is actually unpredictable behavior because there is no guarantee that compilers will organize name
and name2
as I depicted above. In fact, had name2
been organized last, the strcpy
may have violated all sorts of other variables and/or code.
Nowadays, C strcpy
is regarded to be quite unsafe. Modern compilers warn you against calling it directly. They will try to coerce you to use strncpy
instead.