-2

Iam trying to reproduce the behaviour of strlcat in C,writing my own function.

I need to append string1 to the end of string2.

I start looping through string1 until it finds a '\0', and then I try to write string2 to string1 from there. However I think this is not the way to do it because it throw some segmentation fault and maybe Im acessing memor I shouldn't (?).

char *ft_srlcat(char *dst, char *src, int size) {
    int i;
    int j;

    i = 0;
    j = 0;
    while (dst[i] != '\0')
    {
        i++;
    }
    
    while (size > 0 || src[j] != '\0')
    {
        dst[i] = src[j];
        i++;
        j++;
        size--;
    }
    printf("%s\n", dst);
}
void main { 
    ft_strlcat("A very long", "teste to see if it works"), 5
}
Chris
  • 26,361
  • 5
  • 21
  • 42
izzypt
  • 170
  • 2
  • 16
  • 1
    Also, `size` is likely supposed to mean the entire buffer size, and you're decrementing it only for the `src` part. – bereal Nov 29 '22 at 15:28
  • 1
    Does this answer your question? [Appending strings in C](https://stackoverflow.com/questions/12776005/appending-strings-in-c) – wovano Nov 29 '22 at 15:58
  • You can't modify string constants, this causes SEGFAULT. – AR7CORE Nov 29 '22 at 15:59
  • 1
    Technically incorrect, @AR7CORE. The behavior is undefined. A segfault is _likely_ but not required. – Chris Nov 29 '22 at 16:01

1 Answers1

2
  1. Use the correct type for sizes (size_t)
  2. size to make any sense should indicate the dst array length
  3. You cant call this function if dst is not modifiable (const array for example)
  4. When you define function as returning something - return it.
  5. Your function is not null terminating the string if the array is not big enough to accommodate both strings
char *ft_srlcat(char *dst, char *src, size_t size)
{
    char *wrk = size ? dst : NULL;
    if(dst && src)
    {
        while (*dst && size) {dst++; size--;}            
        while (size > 1 && (*dst++ = *src++)) size--;
        if(!size && !*dst) *dst = 0;
    }
    return wrk;
}


int main(void)
{
    char dest[15] = "Hello world.";
    char dest2[5] = "Hello world.";
    char dest1[128] = "Hello world.";
    char dest3[0] = "Hello world.";

    printf("`%s`\n", ft_srlcat(dest, "Goodbye", sizeof(dest)));
    printf("`%s`\n", ft_srlcat(dest2, "Goodbye", sizeof(dest2)));
    printf("`%s`\n", ft_srlcat(dest1, "Goodbye", sizeof(dest1)));
    printf("`%s`\n", ft_srlcat(dest3, "Goodbye", sizeof(dest3)) ? dest3 : "NULL");
    printf("`%s`\n", ft_srlcat(dest1, NULL, sizeof(dest3)) ? dest3 : "NULL");
    printf("`%s`\n", ft_srlcat(NULL, "Goodbye", sizeof(dest3)) ? dest3 : "NULL");
    printf("`%s`\n", ft_srlcat("Hello world.", "Goodbye", sizeof("Hello world.")));
}

https://godbolt.org/z/6xGafsjjo

0___________
  • 60,014
  • 4
  • 34
  • 74