I'm just learning about programming using the C language. Today, I'm trying to code my own strlcpy function and I am facing a problem.
To test my function I compare the results with the "official" function's ones. Everything works fine except... When I put 0 as the len arg. The strcpy function seems to put a garbage character in the destination string and I really don't understand why.
Here is the function's prototype: size_t strlcpy(char * restrict dst, const char * restrict src, size_t dstsize);
Thanks for your help!
Ok. I wanted to make a lot of tests, this is the reason why I'm calling the function inside of a loop.
Here is a part of my main function, testing the function:
do
{
/* Ask for first string */
printf("\nGive me a string (0 to stop): ");
gets(str);
/* Ask for a number */
printf("Now, give me a number please: ");
scanf("%d", &i);
while (getchar() != '\n');
/* I test with the "official function */
j = strlcpy(str2, str, i);
printf("Here is the expected result: %s\n", str2);
printf("Num returned: %d\n", j);
/* Now I test using my function */
j = ft_strlcpy(str3, str, i);
printf("Here is my result: %s\n", str3);
printf("Num returned: %d\n", j);
}while (str[0] != '0');
And here is the function I've coded:
unsigned int ft_strlcpy(char *dest, char *src, unsigned int size)
{
unsigned int cpt;
unsigned int i;
cpt = 0;
i = 0;
while (src[cpt] != '\0')
cpt++;
if (size == 0)
return (0);
while (i < cpt && i < (size - 1))
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
return (cpt);
}
In the function I'm not supposed to call any function from the standard library. My main is just here for testing. The function prototype is given by my teacher, this is the reason why I don't respect the original one.
Sorry fort the time I needed to put my code here and thank you for your help.