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

Sometimes peoples required to create a custom memcpy function for their project. So here in below section, I shall describe a method to create an own memcpy function or you can say that we will see the memcpy implementation in c.

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?

 

If you want to learn more about the c language, here 10 Free days (up to 200 minutes) C video course for you.

Your free trial is waiting

 

memcpy implementation in c

 

Driver program to test the implemented memcpy in c

OutPut:

Message = How Are you?



Leave a Reply