Strcpy when dest buffer is less than src buffer

I am trying to understand the differences / disadvantages of strcpy and strncpy. Can someone help:

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

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

}

Output:

this is a long string 
a long string 

QUESTION: I do not understand how the original sting has changed. According to the explanation, strcpy should continue to copy until it encounters "\ 0", so it is, but where did the line "src" come from.

Please explain.

+5
source share
7 answers

The simple answer is that you have (with strcpy () invoked) something done outside the system specifications and, therefore, really suffers from undefined behavior.

, strcpy() . , :

     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"

D dest, P , 0 - ASCII NUL, .

strcpy (dest, src) (, ):

     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"

.. dest "" " " ( ), src NUL " ".

+11

undefined.

, , dest src . src dest, dest src.

+7

.

dst | | | | | src | | | | | |

, , src .

Howerver , , . , undefined. - / .

Friedrich

+1

- , . , , src .

strncpy().

+1

, , , strncpy , . . strncpy - , - UNIX. , "" strncpy . . , strncpy , , , , . strncpy .

C ( , C89/90) . , - -, strlcpy, strcpy_s .

P.S. StackOverflow strncpy. . UNIX. , . , strncpy .

, strncpy - . C.

+1

:

http://en.wikipedia.org/wiki/Strncpy#strncpy

. strncpy , , .

, strcpy , , , - ​​ . src.

, dst 5 . ? , dest . - src. , , dst.

, !

0

, strcpy:

: , . , strcpy , "\ 0", , src? .

, , strcpy dest, dest, \0. , . strcpy , , \0. , . dest - , null.

strncpy solves this by telling you how big the buffer you are copying to, so that you can avoid cases where it copies more than it can fit.

0
source

All Articles