Processing raw strings in C is always ugly. You have to do two steps to concatenate strings:
Allocate memory for the new string.
Copy the source strings into your new buffer.
As a lesson, please note that there are already three different answers to this question with three different buffer overrun errors.
Here is a function which concatenates two strings and returns a new string:
char *astrcat(const char *x, const char *y)
{
size_t nx = strlen(x), ny = strlen(y);
char *z = malloc(nx + ny + 1);
if (!z)
return NULL;
memcpy(z, x, nx);
memcpy(z + nx, y, ny + 1);
return z;
}
You can expand this to work with three strings, or you can just call it twice. Sane folk tend to use a library or make extensive use of fixed-size buffers.
Alternative: With fixed-size buffers and snprintf
, you get safety and ease of use but you're stuck with fixed size buffers.
const char *x = ..., *y = ...;
char buf[100];
snprintf(buf, sizeof(buf), "%s%s", x, y);
If you don't have snprintf
, then you're probably using MSVC, which has _snprintf
which is almost the same but doesn't always nul-terminate the output.
Don't use strcat
or strcpy
: There are very few circumstances in which strcat
is acceptable:
char buf[100];
strcpy(buf, x); // buffer overflow
strcat(buf, y); // buffer overflow
Don't use sprintf
: It also overflows:
char buf[100];
sprintf(buf, "%s%s", x, y); // buffer overflow