Segmentation fault (core dumped) - strlcpy function C

Viewed 281

I have been building some basic C functions, but Im still not too experienced.

When coding strlcpy function I keep getting a Segmentation fault (core dumped) error. Thought it could have something to do with NUL-terminating strings but I keep getting the error when running.

Any help would be appreciated, thanks in advance.

#include <string.h>
#include <stdio.h>
#include <bsd/string.h>

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

    j = 0;
    while (src[j] != '\0')
        j++;
    
    if (size == 0)
        return (j);

    i = 0;
    while (i < (size - 1) && src[i] != '\0')
    {
        dst[i] = src[i];
        i++;
    }
    dst[i] = '\0';
    return (j);
}

int main()
{
    char *str;

    str = "byes";
    str[3] = '\0';
    printf("%s", str);
    printf("%u", ft_strlcpy("hello", str, 5));
    return (0);
}

Corrected Function in case someone needs it

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

    j = 0;
    while (src[j] != '\0')
        j++;
    
    if (size == 0)
        return (j);

    i = 0;
    while (i < (size - 1) && src[i] != '\0')
    {
        dst[i] = src[i];
        i++;
    }
    dst[i] = '\0';
    return (j);
}

int main()
{
    char str[] = "byes";
    char dest[] = "hello";

    printf("%s\n", str);
    printf("%u\n", ft_strlcpy(dest, str, 5));
    printf("%s\n", dest);

    return (0);
}

That should return:

byes
4
byes
1 Answers

You declared a pointer to a string literal

char *str;

str = "byes";

String literals may not be changed. But you are trying to change the pointed string literal

str[3] = '\0';

that results in undefined behavior.

Remove this statement. The string literal already contains the terminating zero at index equal to 4.

Also in this call

printf("%u", ft_strlcpy("hello", str, 5));

you are again trying to change a string literal using the function ft_strlcpy. At this case it is the string literal "hello".

Declare a character array as for example

char dsn[] = "hello";

and pass it to the function as an argument

printf("%u", ft_strlcpy( dsn, str, sizeof( dsn )));
Related