In C programming the <string.h> strcpy function copies string from one one array to another.The declaration of the function is shown below.
|char *strcpy(char * restrict dst ,|
const char * restrict src);
dst -The pointer to the memory to which the string is to be copied.
src -The pointer to string from which the string is to be copied.
char* -Return the string returned copied to ‘dst’.
Note this function copies the string including the null terminating character.If the memory of the source string and destination string overlap the behavior is undefined.And also it is the programmer’s responsibility to make sure that the destination memory is big enough to accumulate the copied string.
The first code example is a simple example that copies string from one array to another.The second example shows what happen if the memory of source and destination overlap.
st=strcpy( dst , src );
Since the string returned by the function is the string copied to the ‘dst’ memory ‘st’ points to the string same as which is copied to the ‘dst’ memory.
The second example shows a case when the source and destination memory overlap.
st=strcpy( src+4 , src+6 );
Output in VS,
Visual Studio seems to compile the program just fine.And don’t get confuse here with the output,a string starting from the 7th memory block is copied to the memory block starting from the 5th block.And one more thing ‘st’ gives “ring” because only that string is processed by the function.
The function ‘strcpy’ is vulnerable to error in the sense that if the destination memory block is smaller than the source memory block only part of the string will be copied and in this case you may get an unexpected output in your program.So for security reason it is better to use ‘strncpy’ function instead of ‘strcpy’ if the need for either of the function call arises.