#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    5
    Rep Power
    0

    Strcpy behaviour


    Code:
    int main()
    {
        char str[]="hello";
        int i =0;
        char *new;
        while(str[i]){
            printf("str[%d]= %p : %c\n",i,str+i,str[i]);
            i++;
        }
        new =strcpy(str+2,str+1);
        printf("%s\n", new);
        printf(" %p\n",new);
        i = 0;
        while(str[i]){
            printf("str[%d]= %p : %c\n",i,str+i,str[i]);
            i++;
        }
        return 0;
    }
    Output:
    str[0]= 0x7fff4f2572e0 : h
    str[1]= 0x7fff4f2572e1 : e
    str[2]= 0x7fff4f2572e2 : l
    str[3]= 0x7fff4f2572e3 : l
    str[4]= 0x7fff4f2572e4 : o
    eello
    0x7fff4f2572e2
    str[0]= 0x7fff4f2572e0 : h
    str[1]= 0x7fff4f2572e1 : e
    str[2]= 0x7fff4f2572e2 : e
    str[3]= 0x7fff4f2572e3 : e
    str[4]= 0x7fff4f2572e4 : l
    str[5]= 0x7fff4f2572e5 : l
    str[6]= 0x7fff4f2572e6 : o
    copying data from successive locations shoud generate a segfault if character by character is copied
    ( i mean 'e' is copied str+1 to str+2 and then takes 'e' form str+2 copies to str+3 and so on )

    if takes 4 bytes from str+1 and copies to str+2 then
    i should get "ello"

    the output is "eello" , how is it getting extra e.
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,417
    Rep Power
    1871
    > new =strcpy(str+2,str+1);
    Nearly all of the standard library functions have undefined behaviour if you try to do operations on overlapping memory - which is what you're doing here.

    http://www.manpagez.com/man/3/strcpy/
    DESCRIPTION

    The stpcpy() and strcpy() functions copy the string s2 to s1 (including
    the terminating `\0' character).

    The stpncpy() and strncpy() functions copy at most n characters from s2
    into s1. If s2 is less than n characters long, the remainder of s1 is
    filled with `\0' characters. Otherwise, s1 is not terminated.

    The source and destination strings should not overlap, as the behavior is
    undefined.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo