gpt4 book ai didi

c - 我的 strlcpy 版本

转载 作者:太空狗 更新时间:2023-10-29 15:09:59 26 4
gpt4 key购买 nike

海湾合作委员会 4.4.4 c89

我的程序做了很多字符串处理。我不想使用 strncpy,因为它不会终止。而且我不能使用 strlcpy,因为它不可移植。

几个问题。我怎样才能让我的功能适应它的步伐,以确保它完全安全和稳定。单元测试?

这是否足以用于生产?

size_t s_strlcpy(char *dest, const char *src, const size_t len)
{
size_t i = 0;

/* Always copy 1 less then the destination to make room for the nul */
for(i = 0; i < len - 1; i++)
{
/* only copy up to the first nul is reached */
if(*src != '\0') {
*dest++ = *src++;
}
else {
break;
}
}

/* nul terminate the string */
*dest = '\0';

/* Return the number of bytes copied */
return i;
}

非常感谢您的任何建议,

最佳答案

虽然您可以简单地使用另一篇文章推荐的另一个 strlcpy 函数,或者使用 snprintf(dest, len, "%s", src) (它总是终止缓冲区),但这里是我注意到看着你的代码:

size_t s_strlcpy(char *dest, const char *src, const size_t len)
{
size_t i = 0;

这里不需要将 len 设为常量,但它会很有帮助,因为它会检查以确保您没有修改它。

    /* Always copy 1 less then the destination to make room for the nul */
for(i = 0; i < len - 1; i++)
{

糟糕。如果 len 为 0 怎么办? size_t 通常是无符号的,因此 (size_t)0 - 1 最终会变成类似 4294967295 的东西,导致您的例程在程序内存中倾斜并崩溃到未映射的页面。

        /* only copy up to the first nul is reached */
if(*src != '\0') {
*dest++ = *src++;
}
else {
break;
}
}

/* nul terminate the string */
*dest = '\0';

上面的代码对我来说很好。

    /* Return the number of bytes copied */
return i;
}

根据 Wikipedia , strlcpy 返回的是strlen(src)(字符串的实际长度),而不是复制的字节数。因此,您需要继续计算 src 中的字符,直到您点击 '\0',即使它超过了 len

此外,如果您的 for 循环在 len - 1 条件下终止,您的函数将返回 len-1,而不是您期望的 len。


当我写这样的函数时,我通常更喜欢使用起始指针(称为 S)和结束指针(称为 E)。 S 指向第一个字符,而 E 指向最后一个字符 之后 的一个字符(这使得 E - S 是字符串的长度)。虽然这种技术可能看起来丑陋和晦涩,但我发现它相当可靠。

这是我如何编写 strlcpy 的过度评论版本:

size_t s_strlcpy(char *dest, const char *src, size_t len)
{
char *d = dest;
char *e = dest + len; /* end of destination buffer */
const char *s = src;

/* Insert characters into the destination buffer
until we reach the end of the source string
or the end of the destination buffer, whichever
comes first. */
while (*s != '\0' && d < e)
*d++ = *s++;

/* Terminate the destination buffer, being wary of the fact
that len might be zero. */
if (d < e) // If the destination buffer still has room.
*d = 0;
else if (len > 0) // We ran out of room, so zero out the last char
// (if the destination buffer has any items at all).
d[-1] = 0;

/* Advance to the end of the source string. */
while (*s != '\0')
s++;

/* Return the number of characters
between *src and *s,
including *src but not including *s .
This is the length of the source string. */
return s - src;
}

关于c - 我的 strlcpy 版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2933725/

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