Question 7.2

I can't get strcat to work. I tried

	char *s1 = "Hello, ";
	char *s2 = "world!";
	char *s3 = strcat(s1, s2);
but I got strange results.


As in question 7.1, the main problem here is that space for the concatenated result is not properly allocated. C does not provide an automatically-managed string type. C compilers only allocate memory for objects explicitly mentioned in the source code (in the case of ``strings,'' this includes character arrays and string literals). The programmer must arrange for sufficient space for the results of run-time operations such as string concatenation, typically by declaring arrays, or by calling malloc.

strcat performs no allocation; the second string is appended to the first one, in place. Therefore, one fix would be to declare the first string as an array:

	char s1[20] = "Hello, ";

Since strcat returns the value of its first argument (s1, in this case), the variable s3 is superfluous.

The original call to strcat in the question actually has two problems: the string literal pointed to by s1, besides not being big enough for any concatenated text, is not necessarily writable at all. See question 1.32.

References: CT&P Sec. 3.2 p. 32


Read sequentially: prev next up top


This page by Steve Summit // Copyright 1995 // mail feedback