Strings in C. Strcpy acts weirdly

81 views Asked by At

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".

1

There are 1 answers

5
Stephen Quan On

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.