After the input instructions (steps 1-3) above,
- a points to an array of 7 chars ('Hello \0');
- b points to an array of 7 chars ('there \0'); and
- c points to an array of 4 chars ('cat\0').
The two
strcat() calls (steps 4 and 5) will write 9 slots past the original position of the terminating null in the array pointed to by
a. How do you know that array is large enough to hold those extra chars? If it isn't then you're overwriting other variables -- a classic
buffer overflow bug.
You need a buffer large enough to hold the concatenated string. One approach is to use
strlen() to compute how many characters there are (don't forget to count the terminating null) and then
malloc() a big enough buffer. Another way is to statically allocate a buffer that ought to be big enough and then use
strncat() to be sure not to overrun the end of that buffer.
If you use
strncat(), then be careful with the
num argument in successive calls. It needs to decrease as the concatenated string grows. Another issue with
strncat() is that it may not write a terminating null to the output buffer. You should follow each call to
strncat() with an assignment statement that stores null ('\0') in the last slot of the destination buffer.
Another issue arises if the first string is defined with an initializer:
The C Standard allows initialized strings to reside in read-only memory. You will get a run-time error if you use
strcat() or
strncat() to write into read-only memory.