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

How can I fix my custom strlcat terminating with SIGABRT?

有了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++ = '[=10=]';
        n--;
    }
    while (*src++)
        i++;
    return (i);
}

但是当我这样使用 ft_strlcat 时:

#include <stdlib.h>

int main(void)
{
    char *str = "the cake is a lie ! and a liiie[=11=]I'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 ![=11=]I'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 元素数组(用于初始化的字符串加上终止 '[=13=]' 字符)。

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

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

// 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)。