strcpy 和 strncpy 函数的缺陷有哪些?
你如何解决?有替代函数吗?
strcpy复制字符串;并且dest的长度要大于等于src的长度,否则会内存溢出;
那么把最后一个字符制空或者赋值'\0';以'\0'结尾
strncpy复制n个字符;dest的长度大于等于n;最好大于等于strlen(n)+1,1为'\0';否则会内存溢出
memcpy复制任意类型;dest的长度大于等于n,否则会抛出异常;复制的内容有'\0'时,可以赋值'\0',
赋值size长度,用memcpy很方便。
测试代码:
void * memcpy(void *dest, const void *src, int size)
{
assert(dest != NULL && src != NULL);
if ((char*)src >= ((char*)dest + size) || (char*)dest >= ((char*)src + size))//拷贝的dest地址要大于src的地址+拷贝字节长度,
//或者src的地址大于dest的地址
{
char *p_dest = (char*)dest;//设置指针p_dest指向dest
const char *p_src = (const char*)src;//设置p_src指针指向src
while (size--)
{
*p_dest++ = *p_src++;//字符拷贝
}
}
else
{
char *p_dest = (char*)dest + size - 1;
char *p_src = (char*)src + size - 1;
while (size--)
{
*p_dest-- = *p_src--;
}
}
return dest;
}
int main()
{
char src[] = "Hello World!";
char dest[50] = {};
memcpy(dest, src, 10);
cout << dest << endl;
const char *p = "Hello World !";
cout << p << endl;
cout << *(p + 1) << endl;
详解:https://blog.csdn.net/ox0080/article/details/80105497?utm_source=app