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