Implementation of memcpy in c language

Implementation of memcpy in c language

In C language, we generally prefer memcpy to copy n bytes from one memory location to another memory location.In memcpy, we pass the starting address of source and destination buffer to copy n bytes. memcpy perform the forward operation to copy n bytes from source to destination buffer (character array).

Syntax of memcpy in c

Parameters

pvDestination — This is the pointer to the destination buffer, where data is to be copied.
pvSource — This is the pointer to the source buffer, from where data is to be copied.
n — Number of bytes to copy.

Return value

This function returns the pointer to the destination buffer.

Remember the following points before using the memcpy in c

  • size of the destination buffer should be greater than the number of bytes you want to copy.
  • The memory of source and destination buffer should not be overlap.
  •  memcpy does not check the terminating null character, so carefully using with strings.
  • The behavior of memcpy can be undefined if you try to access the destination and source buffer beyond their length.
  • memcpy does not check the validity of the destination buffer.

  • memcpy does not check the validity of the source buffer.

 

See this: Difference between memcpy and memmove.

Simple program to describe how to use memcpy in c

OutPut:

Message = How Are you?

Implement own memcpy in c

Driver program to test the implemented memcpy in c

OutPut:

Message = How Are you?

 

Leave a Reply