this is the source code
int main()
{
char str[]=\"dance\";
char str1[]=\"hello\";
char str2[]=\"abcd\";
strcat(str1,str2);
printf(\"%s\",s
as I have not given the size of str1
, both str1
and str
are present in the memory one after another
like
h e l l o \0 d a n c e
so when I concatenate str1
and str2
following thing happens...
a replaces \0
b replaces d
c replaces a
d replaces n
\0 replaces c
and hence str
is altered
str1
has not enough space to concatenate the string str2
. This invokes undefined behavior. You may get anything. Either expected or unexpected result.
Now try this:
#include <stdio.h>
#include <string.h>
int main(void) {
char str[]="dance";
char str1[10]="hello";
char str2[]="abcd";
strcat(str1,str2);
printf("%s\n",str1);
printf("%s\n",str);
return 0;
}
Output:
helloabcd
dance
This is a "Undefined behavior"
str
, str1
, str2
have a limited size, and they are putted in the stack, the sequence depends on the compiler. You probably have something like this in your stack.
['a']['b']['c']['d']['\0']['h']['e']['l']['l']['o']['\0']['d']['a']['n']['c']['e']['\0']
Got it?
When you writes after the initial size of str1
, you are overriding the stack, an changing all others variable that are on the stack.
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.