0
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??

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 3
    Because `c` is not long enough to hold 5 characters. The way you defined it, it only has length 1. – JS1 Dec 19 '14 at 20:25

4 Answers4

8

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.

M.M
  • 138,810
  • 21
  • 208
  • 365
2

you don't have enough storage for c (only a 1 byte terminator) you are overwriting memory.

try char c[8]="";

1

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.

barak manos
  • 29,648
  • 10
  • 62
  • 114
0

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