Implementation of memcpy in c language

Implementation of memcpy in c language

The memcpy function copies n characters from the source object to the destination object. If the source and destination objects overlap, the behavior of memcpy is undefined. In memcpy, we need to pass the address of source and destination buffer and the number of bytes (n) which you want to copy.

Sometimes peoples require 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:

void *memcpy (void * restrict dst ,const void * src ,size_t n);

Parameters:

src — pointer to the source object

dst — pointer to the destination object

n — Number of bytes to copy.

Return value

This function returns the pointer to the destination buffer (dst).

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.

 

When you will compile the above code you will not get an error if your compiler is not smart but when you will run the code behavior would be undefined because dst is not pointing any valid memory.

 

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

 

In the above code, you will not get the compile-time error but when you will run the program you will get the undefined behavior because the source pointer is not pointing valid memory.

 

See this: Difference between memcpy and memmove.

Simple program to describe how to use memcpy in c

 

In below program src buffer is copying in dst buffer with the help of memcpy.

OutPut:

Message = How Are you?

 

If you want to learn more about the c language, here 10 Free days  C video course for you.
Your free trial is waiting

memcpy implementation in c

Implementation of memcpy is not a big deal, you need to typecast the given source and destination address to char* (1 byte). After the typecasting copy the data from the source to destination one by one until n (given length).

 

Driver program to test the implemented Memcpy in c

In below program src buffer is copying in dst buffer with the help of Memcpy.

OutPut:

Message = How Are you?



Leave a Reply