C programming strcpy string.h


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);

Parameters:
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.

Return type
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.

Code example

char src[20] = “New string” , dst[20] , *st;

st=strcpy( dst , src );

printf(“dst=%s”, dst);
printf(“\nst=%s”, st);

Output,

dst=New string
st=New string

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.

Code example

char src[20] = “New string” , *st;

st=strcpy( src+4 , src+6 );

printf(“src=%s”, src);
printf(“\nst=%s”, st);

Output in VS,

src=New ring
st=ring

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.


*Side Note

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.


Related links

->C strncpy string.h

->C memmove string.h

->C memcpy string.h