strcpy when dest buffer is smaller than src buffer

user193891 picture user193891 · Oct 21, 2009 · Viewed 13k times · Source

I am trying to understand the difference/disadvantages of strcpy and strncpy. Can somebody please help:

void main()
{
char src[] = "this is a long string";
char dest[5];

strcpy(dest,src) ;
printf("%s \n", dest);
printf("%s \n", src);

}

The output is:

this is a long string 
a long string 

QUESTION: I dont understand, how the source sting got modified. As per explanation, strcpy should keep copying till it encounters a '\0', so it does, but how come "src' string got modified.

Please explain.

Answer

ndim picture ndim · Oct 21, 2009

The easy answer is that you have (with that strcpy() call) done something outside the specifications of the system, and thus deservedly suffer from undefined behaviour.

The more difficult answer involves examining the concrete memory layout on your system, and how strcpy() works internally. It probably goes something like this:

     N+28 "g0PP"
     N+24 "trin"
     N+20 "ng s"
     N+16 "a lo"
     N+12 " is "
src  N+08 "this"
     N+04 "DPPP"
dest N+00 "DDDD"

The letters D stand for bytes in dest, the letters P are padding bytes, the 0 characters are ASCII NUL characters used as string terminators.

Now strcpy(dest,src) will change the memory content somewhat (presuming it correctly handles the overlapping memory areas):

     N+28 "g0PP"
     N+24 "trin"
     N+20 "g0 s"
     N+16 "trin"
     N+12 "ng s"
src  N+08 "a lo"
     N+04 " is "
dest N+00 "this"

I.e. while dest now "contains" the full string "this is a long string" (if you count the overflowed memory), src now contains a completely different NUL-terminated string "a long string".