Yes, you need to allocate memory to totalLine
. In C you have a wide range of options of varying levels of awkwardness. My preferred way requires the GNU library extension asprintf
(also available on the BSDs, but not included in POSIX):
char *xconcat2(const char *line1, const char *line2) {
char *totalLine;
int len = asprintf(&totalLine, "%s%s", line1, line2);
if (len < 0) abort();
return totalLine;
}
I prefer to do it this way because it's compact, easy to read, and easy to modify. If you need to stick to strict ISO C, though, in my opinion the next best thing is to write out a series of strlen
and memcpy
operations. I don't like to use strcpy
, strncpy
, strcat
, or strncat
at all, because it's very easy to be accidentally quadratic with strcat
and strncat
, because it's hard to be sure you don't have a buffer overflow bug with them, and because strncpy
and strncat
don't do what you might expect them to do.
char *xconcat2_iso(const char *line1, const char *line2) {
size_t len1 = strlen(line1);
size_t len2 = strlen(line2);
char *totalLine = malloc(len1 + len2 + 1);
if (!totalLine) abort();
memcpy(totalLine, line1, len1);
memcpy(totalLine + len1, line2, len2);
totalLine[len1 + len2] = '\0';
return totalLine;
}
In C++, as recommended in the accepted answer, just use std::string
.