this is the source code
int main()
{
char str[]=\"dance\";
char str1[]=\"hello\";
char str2[]=\"abcd\";
strcat(str1,str2);
printf(\"%s\",s
You are concatenating str2
to str1
, but str1
is not big enough to hold both strings. There is a buffer overflow that corrupts the contents of the third string on the stack, str
.
When you define
char str1[] = "hello";
you create an array of six chars, 5 for "hello" plus one null character to terminate the string. The string is already full, so to speak. A quick fix is to specify an array size:
char str1[20] = "hello";
Now you should be able to append str2
to str1
with strcat
.
In practice, you should ensure that the buffer is big enough to hold the whole string:
char buf[20];
if (strlen(str1) + strlen(str2) < 20) {
strcpy(buf, str1);
strcat(buf, str2);
}
This is tedious. There is another way to concatenate strings without buffer overflow:
char buf[20];
int n;
n = snprintf(buf, 20, "%s%s", str1, str2);
This might cut the whole string short, but will not overflow the buffer. The return value n
tells how many characters would have been written, had there been enough space, so you can use it to check.