I am currently learning C. One of the things I want to do in order to get better is to mimic the "strcat" function from the header. In order to make a more precise copy I compare the output of my own function with the output of the original one. They use identical, but different char arrays. However, the output of my own function changes if it is called after the original one. Here are the two code variations:
In the first one the output of the original is "1234567890123456", as expected, and the output of my own is "123456789123456". I have found after several dozens of various checks: the '0' char disappears from the src[0] once it is passed to the function as a parameter:
int main()
{
char dest[10] = "123456789";
char src[70] = "0123456";
printf ("Concatenate |%s| and |%s|\n", dest, src);
char dest1[10] = "123456789";
char src1[70] = "0123456";
printf ("Normal people do: %s\n", strcat(dest1, src1));
printf ("Your filthy code: %s\n", ft_strcat(dest, src));
return 0;
}
However, if I simply relocate the printf of my function like this:
int main()
{
char dest[10] = "123456789";
char src[70] = "0123456";
printf ("Concatenate |%s| and |%s|\n", dest, src);
printf ("Your filthy code: %s\n", ft_strcat(dest, src));
char dest1[10] = "123456789";
char src1[70] = "0123456";
printf ("Normal people do: %s\n", strcat(dest1, src1));
return 0;
}
both functions will return "1234567890123456" as an output.
The question is: how is this possible? I am curious because these functions address two different sets of arrays and therefore should not affect one another. For some reason my function's behaviour varies depending on when it is called in the body of the int main().
Please notice, that I have intentedly made the dest[] array 10 chars big, as I want to mimic the behaviour of original "strcat" in unexpected situations as well. Although that is probably the core of the problem, and if I change it, the code works fine in both aforementioned cases. As I said, I am interested in the nature of the problem, not in the way to solve it.
I am not sure whether the text of my function is relevant for this issue, but here it is, just in case:
char *ft_strcat(char *dest, char *src)
{
int dest_end;
int src_count;
dest_end = 0;
src_count = 0;
while (dest[dest_end])
dest_end++;
while (src[src_count])
{
dest[dest_end] = src[src_count];
src_count++;
dest_end++;
}
dest[dest_end + 1] = '\0';
return dest;
}
Thank you for any answers.