目标缓冲区 小于 实际缓冲区
char *name = "1234567890";
char name2[6]={0};
memcpy_s( name2 , sizeof(name2) , name, strlen(name));
动态执行失败 (DEBUG ASSERTION FAILED !) 运行库和调试库都会提示出错.
注意: 指针sizeof( 指针 ) = 4
strncpy(name2,name ,sizeof(name) ); 打印name2 1234
strncpy(name2,name ,strlen(name) ); 打印name2 123456IOIPNUUY
优化这个语句,尽量拷贝内容
strncpy(name2,name , strlen(name)>sizeof(name2)? sizeof(name2): strlen(name) );
目标缓冲区 小于 实际缓冲区
strncpy(name2,name ,sizeof(name2)-1 );
sizeof(name2)-1 ------------>让最后一个name2字符留给\0 否则这个字符也被拷贝了.
看一下LINUX下的两个函数的源代码,印象会更加深刻一些
void * memcpy(void * dest,const void *src,size_t count)
{
char *tmp = (char *) dest, *s = (char *) src;
while (count--)
*tmp++ = *s++;
return dest;
}
char * strcpy(char * dest,const char *src)
{
char *tmp = dest;
while ((*dest++ = *src++) != '\0')
/* nothing */;
return tmp;
}
老实讲,这两个函数长得是很帅
参考
http://stackoverflow.com/questions/4593907/difference-between-strncpy-and-memcpy
http://www.cppblog.com/Tim/archive/2011/04/02/143259.aspx