With ft_strlcat
I want to re-write srlcat
. This is what I have so far:
#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);
}
But when I use ft_strlcat
like this:
#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);
}
I get the following 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)
What do I need to change in order to fix this?
With
char buff2[] = "there is no stars in the skyline";
you explicitly create an array of 33
elements (the string you use for initialization plus the terminating '\0'
character).
Any attempt to append to that string will write out of bounds and lead to undefined behavior.
If you want to append to the string, you need to make sure that the size of the array is large enough, like e.g.
// Create an array which can fit 128 characters, including the terminator
char buff2[128] = "there is no stars in the skyline";
You also use sizeof(buff2)+20
as the length of the destination buffer in your call, and this is wrong as you then say that the destination buffer is 20 elements larger than it really is. You should only use sizeof buff2
as the size (or possibly sizeof buff2 - 1
if the size doesn't include the terminator).