The strcpy function works weirdly and I want to know what is happening.
char name[] = "The Batman"; //10 characters
char name2[5];
strcpy(name2, name);
name is now changed for some reason. It is now "atman". Why is name changing over here? name2 however is successfully been assigned to "The batman". How is it possible since name2 isn't large enough to hold "The Batman".
Before
strcpy:After
strcpy:i.e. the
strcpyoverrun the memory allocated byname2onto the start ofnamerewriting the contents at the start.Of course, when you print
name, the print will stop at\0and will only show "atman".When you print
name2it will exceed the 5 characters you assigned and overrun intonamememory 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
nameandname2as I depicted above. In fact, hadname2been organized last, thestrcpymay have violated all sorts of other variables and/or code.Nowadays, Cstrcpyis regarded to be quite unsafe. Modern compilers warn you against calling it directly. They will try to coerce you to usestrncpyinstead.