main()
{
char a[]="abss";
char c[]="";
strcpy(c,a);
printf("%s",a);
}
Why does the source string a
change on using strcpy()
it is checked only when string c
is greater than or equal to string a
??
main()
{
char a[]="abss";
char c[]="";
strcpy(c,a);
printf("%s",a);
}
Why does the source string a
change on using strcpy()
it is checked only when string c
is greater than or equal to string a
??
c
has size 1
but you try to copy 5 characters into it. This causes undefined behaviour.
To explain what you are seeing, probably what happens is that c
and a
are stored next to each other in memory, so the things you write into c
overflow and land in a
.
you don't have enough storage for c (only a 1 byte terminator) you are overwriting memory.
try char c[8]="";
Official answer:
The memory allocated for the destination string is 1 character, and the length of the source string is 5 characters. So you are invoking undefined behavior by the C-language standard.
Practical answer:
The memory allocated for the destination string is 1 character, and the length of the source string is 5 characters. Your specific compiler has probably allocated the source string immediately after the destination string in memory. So the first character is successfully copied into the destination string, and the remaining 4 characters are copied into the source string itself.
Please note that you have yet another problem, as the destination string is no longer null-terminated.
You need to allocate memory for the destination which is unallocated. In your case it should be
char[8] c;
and it should work fine