gpt4 book ai didi

c - 如何修复我的自定义 strlcat 以 SIGABRT 终止?

转载 作者:太空宇宙 更新时间:2023-11-04 03:08:57 25 4
gpt4 key购买 nike

有了ft_strlcat我想重写srlcat。这是我目前所拥有的:

#include <stdlib.h>

size_t ft_strlcat(char *dest, const char *src, size_t n)
{
size_t i;

i = 0;
while (*dest && n > 0)
{
(void)*dest++;
i++;
n--;
}
while (*src && n > 1)
{
*dest++ = *src++;
i++;
n--;
}
while (n > 0)
{
*dest++ = '\0';
n--;
}
while (*src++)
i++;
return (i);
}

但是当我像这样使用 ft_strlcat 时:

#include <stdlib.h>

int main(void)
{
char *str = "the cake is a lie ! and a liiie\0I'm hidden lol\r\n";
char buff1[] = "there is no stars in the skyline";
char buff2[] = "there is no stars in the skyline";
size_t max = strlen("the cake is a lie !\0I'm hidden lol\r\n") + 4;
//size_t r1 = strlcat(buff1, str, max);
size_t r2 = ft_strlcat(buff2, str, sizeof(buff2)+20);

printf("\nOriginal |%zu|\nMy |%zu|\n", r2);
printf("%s\n", buff2);
printf("%zu", max);

return (0);
}

我得到以下 SIGABRT:

Process terminating with default action of signal 6 (SIGABRT): dumping core
at 0x506FC37: raise (raise.c:56)
by 0x5073027: abort (abort.c:89)
by 0x50AC2A3: __libc_message (libc_fatal.c:175)
by 0x514787B: __fortify_fail (fortify_fail.c:38)
by 0x514781F: __stack_chk_fail (stack_chk_fail.c:28)
by 0x4007BC: main (usercode.c:44)

我需要更改什么才能解决此问题?

最佳答案

char buff2[] = "there is no stars in the skyline";

您显式创建了一个包含 33 元素的数组(用于初始化的字符串加上终止符 '\0')。

任何附加到该字符串的尝试都将越界写入并导致未定义的行为。

如果你想附加到字符串,你需要确保数组的大小足够大,例如

// Create an array which can fit 128 characters, including the terminator
char buff2[128] = "there is no stars in the skyline";

您还使用 sizeof(buff2)+20 作为调用中目标缓冲区的长度,这是错误的,因为您随后说目标缓冲区比实际大 20 个元素.您应该只使用 sizeof buff2 作为大小(如果大小不包括终止符,则可能使用 sizeof buff2 - 1)。

关于c - 如何修复我的自定义 strlcat 以 SIGABRT 终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58507021/

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