char src[5]="abcd";
char *des=new char[str.length(src)+1]; // length()不计\0
strcpy_s(des,length(src),src); // 崩溃
strcpy_s(des,length(src)+1,src); // √
因为strcpy_s的边界保护机制 size(src)<=复制size<=size(des)
strcpy_s源码:
1 errno_t __cdecl _FUNC_NAME(_CHAR *_DEST, size_t _SIZE, const _CHAR *_SRC) 2 { 3 _CHAR *p; 4 size_t available; 5 6 /* validation section */ 7 _VALIDATE_STRING(_DEST, _SIZE); 8 _VALIDATE_POINTER_RESET_STRING(_SRC, _DEST, _SIZE); 9 10 p = _DEST; 11 available = _SIZE; 12 while ((*p++ = *_SRC++) != 0 && --available > 0) 13 { 14 } 15 16 if (available == 0) 17 { 18 _RESET_STRING(_DEST, _SIZE); 19 _RETURN_BUFFER_TOO_SMALL(_DEST, _SIZE); 20 } 21 _FILL_STRING(_DEST, _SIZE, _SIZE - available + 1); 22 _RETURN_NO_ERROR; 23 }
当源字符串_SRC不到\0字符,复制长度available减到0时,有边界测试会引发断言。 是strcpy的安全版本,其他的str类型函数也有安全版本。
strcpy复制到src的\0字符停止,但是当size(dest)<size(src)时,只要两个指针指向的内存可读写,循环就可以继续下去,会超出Dest的边界覆盖其他内存。
复制char[]无\0字符时,会一直复制到遇到下一个\0字符。 用char[]保存字符串,在最后加上\0,
否则strcpy边界不对时,会有隐形错误。或者在strcpy之后给char[]加上\0
char* p="how are you ?";
char name[10];
strcpy(name,p);
name[sizeof(name)-1]='"0'
strncpy源码:
1 char *strncpy(dest, source, count) - copy at most n characters 2 ; 3 ;Purpose: 4 ; Copies count characters from the source string to the 5 ; destination. If count is less than the length of source, 6 ; NO NULL CHARACTER is put onto the end of the copied string. 7 ; If count is greater than the length of sources, dest is padded 8 ; with null characters to length count. 9 ; 10 ; Algorithm: 11 ; char * 12 ; strncpy (dest, source, count) 13 ; char *dest, *source; 14 ; unsigned count; 15 ; { 16 ; char *start = dest; 17 ; 18 ; while (count && (*dest++ = *source++)) 19 ; count--; 20 ; if (count) //如果count大于零 即count is greater than the length of sources,'\0'已写入,不够的字符数都填充\0 21 ; while (--count) 22 ; *dest++ = '\0'; 23 ; return(start); 24 ; } 25 ; 26 ;Entry: 27 ; char *dest - pointer to spot to copy source, enough space 28 ; is assumed. 29 ; char *source - source string for copy 30 ; unsigned count - characters to copy 31 ; 32 ;Exit: 33 ; returns dest, with the character copied there. 34 ;
strcpy(des,src,size);
size<src长度时,des最后字符无\0,打印时会乱码直到遇到\0
size>src长度时,不够的位全部补充\0