Search code examples
cstringcopying

Error Copying 1 string to another in C


  • I was trying to copy the contents of 1 string to another (a into b) . I deliberately took the second string(b) to be smaller than the 1st one(a) .
  • I copied the contents of the first one into second

    . I added WATCH on both of them . In the Debug tab , I found out that while copying the original string gets destroyed and the new one also DISPLAYED LARGER than its size.

       #include<stdio.h>
       int main()
       {
     char a[10]="What?";
     char b[2];
     int i;
     for(i=0;i<6;i++)
     {
        b[i]=a[i];
     }
     printf("This is %s",a);
     printf("\n this is b now: ",b);
     return 0;
    

    }

  • I have attached the screenshot for the same. I took a = a string of size 10 . a="WHat?" then I took a string b[2]

  • After copying , I printed both a and b . I expected the output to be , a = "WHat?" , b="WH" But the output is coming something else.(See the screenshot)

Why did the original string get destroyed ? Has the pointer changed ? But I have made it a constant pointer .It can't be changed.

Here is the Screen shot to the problem I am facing : https://www.dropbox.com/s/8xwxwb27qis8xww/sjpt.jpg

Please Help Somebody !!


Solution

  • As pointed out in other answers, you are writing outside the bounds of the array. The original string a changes because it happens to be exactly after b in memory as you can see in the debug window.

    Before the loop, memory looks like this:

     b  a
    |00|WHat?00000|
    

    After the loop, memory looks like this:

     b  a
    |WH|at?0?00000|
    

    This explains why

    • a is changed
    • the original questionmark in a is still there (you only write 6 characters - two into the location reserved for b, 4 (including null terminator) into the location of a)

    Of course this is undefined behavior as already mentioned by Vlad Lazarenko, but it explains the behavior for your compiler/settings/version/etc.

    A constant pointer only exists for the compiler. It ensures that you cannot explicitly manipulate its data, but if you have memory leaks, nothing can be guaranteed.