When you write char* s = "something"
a piece of read-only memory is allocated. More on this here.
The declaration of strcat
looks like this:
char *strcat( char *dest, const char *src );
Basically what it will do is append src
to dest
, but since your destination, str1
does not have enough memory to hold both strings.
So what I would do is, either use snprintf
with a pre-allocated buffer or:
char *str1 = "United";
char *str2 = "Front";
char *buf = calloc(strlen(str1) + strlen(str2) + 1, sizeof(char));
strncpy(buf, str1, strlen(str1));
strncat(buf, str2, strlen(str2));
printf("%s", buf);
Or with snprintf
:
char *str1 = "United";
char *str2 = "Front";
int buf_len = strlen(str1) + strlen(str2) + 1;
char *buf = calloc(buf_len, sizeof(char));
snprintf(buf, buf_len, "%s%s", str1, str2);