gpt4 book ai didi

c - strlcpy 还是 memcpy?

转载 作者:太空宇宙 更新时间:2023-11-04 07:32:19 28 4
gpt4 key购买 nike

我知道 strcpy 在处理缓冲区时不安全,但是在我的代码中我有这个

static char    buf[HUGE_BUFFER_SIZE + 1];
char servername[200];
int length = 0;
char *out = NULL;
length = strlen(buf);
out = alloca(strlen(servername) + length + 5);
length = strlen(servername);
strcpy(out, servername);
out[length] = ' ';
out[length + 1] = 0;
strcat(out, buf);

如果我将 strcpy 更改为 strlcpy 并对 arg3 使用 sizeof,则输出会出现乱码。有没有比使用 memcpy 更简单的方法(看起来我可能必须这样做?)我试图避免使用不安全的函数,如 strcpy 和 friend 。有没有一种更简单的方法可以通过更少的函数复制和 strnlens/alloca 来完成上述任务?

最佳答案

使用 snprintf() 可能更简单:

char out[1000];  // Or however large you need.
int len = snprintf(out, sizeof(out), "%s %s", servername, buf);
if (len >= sizeof(out)) {
// Result would have overflowed the buffer and has been truncated.
}

注意 >= 而不是条件中的 >

snprintf() 返回写入文本的长度,不包括终止空字节。因此,如果返回值等于缓冲区大小,则意味着最后一个字符被截断(因为 snprintf() 总是以 null 终止结果字符串)。

关于c - strlcpy 还是 memcpy?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12613651/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com