I created a program to concatenate two strings. However I get some extra characters included in the output string when the char array is too small.
Faulty code below:
char c[3] = "abc";
char d[3] = "def";
char result[8];
strcpy(result, c);
strcat(result, d);
printf("%s\n, result);
Prints abc{def�
Running the program without recompiling gives random chars each time. E.g abc�tdef�
.
Changing the size of the result variable makes no difference:
char c[3] = "abc";
char d[3] = "def";
char result[6];
givesabcrdef�
I know that I need to change the size of the char arrays to 'c[4]' to produce expected output. This is to have space for null termination?
Furthermore, why are those symbols added? What decides why exactly those chars were included when they appear to be randomly selected?
Why does the result array acceept more chars than written? E.g 'char result[1]' gives 'abcdef' as output.
I've tried googling for answers.