C programming memcpy string.h

In C programming the <string.h> mempy function copies a memory block of specific size from one destination to another.The declaration of the function is given below.

void *memcpy(void * restrict dest ,
const void * restrict source ,
size_t n);

dest -This is the pointer to the destination memory block where the values is to be copied.

source -This is the pointer to the source memory block from where the value is to be copied.

n -The number of characters to be copied.

Return type
void* -Returns the value pointed by ‘destination’ pointer or the value copied to the memory block.

Note the memory pointed by the ‘dest’ and ‘source’ pointer must be at least ‘n’ byte apart to avoid overlapping;otherwise the function’s behavior is undefined.

Code example

char dest[20] , source[]=”New string” ;

void *vd ;

vd=memcpy(dest, source , sizeof(source) ); //sizeof gives the number of characters;counting the last ‘\0’ character

printf(“*dest=%s”, dest) ;
printf(“\n*vd=%s”, (char*)vd); //converting ‘vd'(void pointer) to ‘char*’ type is necessary


*dest=New string
*vd=New string

In the above program,if you are using ‘strlen’ instead of ‘sizeof’ in the third argument you must add 1 to it since ‘strlen’ returns the number of characters not counting the last ‘\0’ null character.If 1 is not added the output may be not what you expected.Consider running the code below.

Code example

char dest[20] , source[]=”New string” ;

void *vd ;

vd=memcpy(dest , source , strlen(source)+1 );

printf(“*dest=%s”, dest) ;

Output in Visual Studio,

*dest=New string╠╠╠╠╠╠╠╠╠╠╠╠╠╠ääJK≡°O

The extra characters after the “New string” is undefined.Now try adding 1 to the third argument in the ‘memcpy’ call,the output is exactly the string copied.When 1 is not added the last ‘\0’ character is not copied to the destination memory block.Since this last character-which signal the end of the string- is not copied the compiler deduce that more characters should be copied to the ‘dest’ array since the ‘dest’ array can hold more characters.So it simply copies the garbage values found in that extra memory block and output them.

As said earlier when using ‘memcpy’ function if the source and destination memory block overlap the behavior is undefined.An example of such case is given below.

Code example

char str[] = “The new string” ;

char *mem = (char*)malloc( strlen(a) + 1 );

memcpy(mem, a, strlen(a) + 1); //copies the str array to ‘mem’pointed memory

printf(“%s”, mem);

memcpy( mem+4 , mem+8 , 7);

printf(“\n%s”, mem);

free( mem );

Output in VS,

The new string
The string

In the second ‘memcpy’ the source and destination memory overlap;which is the same memory pointed by ‘mem’ pointer,but fortunately the VS seems to compile just fine,however,your IDE may not agree with this so try running the program in your compiler.

Related links

->C memmove string.h

->C malloc stdlib.h

->C free stdlib.h

->C strcpy string.h