What you should have written, code-wise, answers your question:
char *str1 = "India";
char *str2 = "BIX";
//should have been
const char *str1 = "India";
const char *str2 = "BIX";
The variables str1
and str2
are being assigned the address in memory where the string CONSTANTS India
and BIX
are located. This memory is read-only. You are trying to concatenate these two strings using strcat
. Ok, look at what it does:
strcat(str1, str2);
/\ take this
|| copy ||
===========
add to end
This requires str1
to point to a block of memory big enough to accomodate both itself and the chars that you're concatenating onto it. In case of string literals, this is never the case.
Also remember how I wrote your code with the const
storage class specifier? Now look at strcat
's prototype:
char * strcat(char * destination, const char *source);
The function expects the first argument to be a regular char *
, not a const. This tells you the function will attempt to change the memory the pointer points to. As others have pointed out, and I mentioned above: the memory your str1
pointer points to is read only, hence the segfault.
What you could write is:
char str1[15] = "India";
const char *str2 = "BIX";
strcat(str1, str2);
That ought to work. Note that strcat
does not check/prevent overflow. The size of the destination memory should be big enough to accomodate strlen(source) + strlen(destination) + 1
. Using strncat
instead would be better, still! It allows you to specify a max number of chars to be concatenated onto the destination string:
size_t free_space = 15;
char str1[free_space] = "India";
const char *str2 = "BIX";
free_space -= strlen(str1) + 1;//add 1 here, to ensure we'll have room for the terminating \0 char
char *str3 = strncat(
str1,
str2,
free_space
);
//now we've concatenated something onto our string, keep track of free space left:
free_space -= strlen(str2);//dangerous, though -> size_t is unsigned, perhaps best do:
size_t src_len = strlen(str2);
char *str3 = strncat(
str1,
str2,
free_space
);
if (src_len >= free_space)
free_space = 0;
else
free_space -= src_len;