C program produces weird output C program produces weird output unix unix

C program produces weird output


You aren't leaving enough room for a null terminator in catfish[9] when you strcpy "Big Fish\n". That string is 9 characters long, which means you need a size-10 buffer to store the null-terminator.

If a string misses the null terminator the output has undefined behaviour since the program has no way to know where the string ends.


When you perform the first copy, strcpy() copies in total 10 bytes (9 from the string itself plus the terminator). As you have allocated only 9 bytes in catfish, the terminator goes into the first byte of goldfish, which then gets overwritten when you copy the second string. Hence, when you do a printf() of catfish, it doesn't stop at the end of catfish but keeps printing until it finds the terminator at the end of goldfish.

In the second case you add enough space for the terminator not to be overwritten so when you print it will just print the contents of catfish as expected.