
September 18th, 2012, 09:55 AM
|
|
Registered User
|
|
Join Date: Sep 2012
Posts: 5
Time spent in forums: 1 h 31 sec
Reputation 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;
}
Quote: 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.
|