我的 strcpy
函数有问题。我在不使用 string.h
header 的情况下编写它。它可以工作,但是,如果 dst 比 src 短怎么办?我怎么检查呢?因为如果 dst 是 example "car"
和 src "green"
会出错吗?
#include <stdio.h>
#include <stdlib.h>
char* strcpy(char* dst, const char* src) {
char* origDest =dst;
while(*src != '\0') {
*dst = *src;
dst++;
src++;
}
return origDest;
}
int main()
{
char A[] = {"Blackcar"};
char B[] = {"white"};
char *C[10];
*C = strcpy(&A, &B);
printf("%s", *C);
return 0;
}
此外,我应该将 malloc
与此函数一起使用吗?
最佳答案
无法以优雅的方式检查它,因为您无法知道 strcpy
中的 dst
的长度。也许在你的主函数中,你可以检查字符串 A
的长度并终止 \0
,但不能保证 dst
可能不是垃圾数据或被清除使用 \0
。这就是为什么 strcpy
很容易导致缓冲区溢出的原因之一 ( Why should you use strncpy instead of strcpy? )
所以我的建议是在你的函数中添加一个 length
参数,这意味着将复制多少字节。或者您可以自己实现一个版本的 strncpy
。
PS:即使使用 strncpy
,程序员也必须确保传递给 strncpy
的参数有效且正确。
关于c - 实现 strcpy : what if the destination is shorter than the source?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27459647/