strcpy_s

时间:2023-03-09 05:39:35
strcpy_s

  

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源码:

 errno_t __cdecl _FUNC_NAME(_CHAR *_DEST, size_t _SIZE, const _CHAR *_SRC)
{
_CHAR *p;
size_t available; /* validation section */
_VALIDATE_STRING(_DEST, _SIZE);
_VALIDATE_POINTER_RESET_STRING(_SRC, _DEST, _SIZE); p = _DEST;
available = _SIZE;
while ((*p++ = *_SRC++) != && --available > )
{
} if (available == 0)
17 {
_RESET_STRING(_DEST, _SIZE);
_RETURN_BUFFER_TOO_SMALL(_DEST, _SIZE);
}
_FILL_STRING(_DEST, _SIZE, _SIZE - available + );
_RETURN_NO_ERROR;
}

当源字符串_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源码:

 char *strncpy(dest, source, count) - copy at most n characters
;
;Purpose:
; Copies count characters from the source string to the
; destination. If count is less than the length of source,
; NO NULL CHARACTER is put onto the end of the copied string.
; If count is greater than the length of sources, dest is padded
; with null characters to length count.
;
; Algorithm:
; char *
; strncpy (dest, source, count)
; char *dest, *source;
; unsigned count;
; {
; char *start = dest;
;
; while (count && (*dest++ = *source++))
; count--;
; if (count) //如果count大于零 即count is greater than the length of sources,'\0'已写入,不够的字符数都填充\0
; while (--count)
; *dest++ = '\0';
; return(start);
; }
;
;Entry:
; char *dest - pointer to spot to copy source, enough space
; is assumed.
; char *source - source string for copy
; unsigned count - characters to copy
;
;Exit:
; returns dest, with the character copied there.
;

strcpy(des,src,size);

size<src长度时,des最后字符无\0,打印时会乱码直到遇到\0

size>src长度时,不够的位全部补充\0