===============================================================
char buffer1[10]="12345678";
char *pt = "hello1234567abcdefghijkABCDEFGHIJK!!!";
strlen(buffer1) is 8
strlen(length) is 37
===============================================================
char *strcpy(char *s1, const char *s2);
The strcpy() function copies string s2 to s1, including the
terminating null character, stopping after the null charac-
ter has been copied.
所以,当目标长度大于源时,会导致溢出,在Linux中,会捕捉到,有“Segmentation fault”的异常。
Solaris中没捕捉到。
strcpy(buffer1,pt);
printf ("strcpy:buffer1=%s, length=%d/n",buffer1, strlen(buffer1));
--
Output on Solaris:
strcpy:buffer1=hello1234567abcdefghijkABCDEFGHIJK!!!, length=37
Output on RedHat:
strcpy:buffer1=hello1234567abcdefghijkABCDEFGHIJK!!!, length=37
Segmentation fault
使用时要注意长度,否则会有溢出。
===============================================================
char *strncpy(char *s1, const char *s2, size_t n);
The strncpy() function copies exactly n
bytes, truncating s2 or adding null characters to s1 if
necessary. The result will not be null-terminated if the
length of s2 is n or more. Each function returns s1.
当n等于或者大于源长度时,完成copy后,目标串没有'/0',Linux会捕捉到,有“Segmentation fault”的异常。
Solaris中没捕捉到。
strncpy(buffer1,pt,strlen(pt));
printf ("strncpy:buffer1=%s, length=%d/n",buffer1, strlen(buffer1));
--
Output on Solaris:
strncpy:buffer1=hello1234567abcdefghijkABCDEFGHIJK!!!???, length=40
Output on RedHat:
strcpy:buffer1=hello1234567abcdefghijkABCDEFGHIJK!!!?í???í?f?N, length=47
Segmentation fault
安全的写法是:
strncpy(buffer1,pt,sizeof(buffer1)-1);
buffer1[sizeof(buffer1)-1] = '/0';
printf ("strncpy:buffer1=%s, length=%d/n",buffer1, strlen(buffer1));
Output:
strncpy:buffer1=hello1234, length=9
===============================================================
size_t strlcpy(char *dst, const char *src, size_t dstsize);
The strlcpy() function copies at most dstsize-1 characters
(dstsize being the size of the string buffer dst) from src
to dst, truncating src if necessary. The result is always
null-terminated. The function returns strlen(src). Buffer
overflow can be checked as follows:
if (strlcpy(dst, src, dstsize) >= dstsize)
return -1;
Note: strlcpy is not ANSI C! 有些编译器不支持。
结果强制有"/0"结束。
int bytecopy = strlcpy(buffer1,pt,strlen(pt));
printf ("strcpy:buffer1=%s, length=%d, bytecopy=%d/n",buffer1, strlen(buffer1),bytecopy);
Output:
strcpy:buffer1=hello1234567abcdefghijkABCDEFGHIJK!!, length=36, bytecopy=37
char buffer1[10]="12345678";
char buffer3[5]="123";
int bytecopy = strlcpy(buffer1,buffer3,strlen(buffer3));
printf ("strcpy:buffer1=%s, length=%d, bytecopy=%d/n",buffer1, strlen(buffer1),bytecopy);
Output:
strcpy:buffer1=12, length=2, bytecopy=3
===============================================================