Reputation: 2101
I am currently writing a program where i was stuck in a different kind of behaviour of strcpy() function . Here is short demo of it...
I went through the following question : Strip first and last character from C string
//This program checks whether strcpy() is needed or not after doing the modification in the string
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[] = "Nmy stringP";
char *p = mystr ;
p++;
p[strlen(p)-1] = '\0';
strcpy(mystr,p);
printf("p : %s mystr: %s\n",p,mystr);
}
Output :-
p : y strnng mystr: my strnng
If i dont use strcpy() function , then i get
p : my string mystr : Nmy string
Why is this happening ??
Upvotes: 2
Views: 3108
Reputation: 5389
You can not use strcpy
with overlapping memory locations i.e., if source and destination strings overlap. In this case, the behavior is undefined as stated in the standards.
But you can use a temp
memory location to do the swap like this
Upvotes: 1
Reputation: 182619
The standard says:
7.24.2.3
If copying takes place between objects that overlap, the behavior is undefined.
You could use memmove
or a different method altogether.
Upvotes: 10