Implementation of memcpy in C language

Implementation of memcpy in c language

In this blog post, you will learn about the C memcpy() function with the help of programming examples. You will also see how to create your memcpy function in C.

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 the source and destination buffer and the number of bytes (n) that you want to copy.

Syntax memcpy in C:

The below syntax was until the introduction of C99 standards,

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

 

The below syntax is since the C99 standards,

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

 

Note: The only difference in both syntaxes is that since C99 restrict keyword is using in the memcpy function prototype. The restrict type qualifier, introduced in C99 and it is a special type of qualifier and can be applied to pointer declarations. It makes the address location unique to a single pointer.

 

memcpy Parameters:

The memcpy() function accepts the following parameters:

dst — pointer to the destination object

src — pointer to the source object

n — Number of bytes to copy.

 

Return value of memcpy() in C:

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

 

 

Example program to describe how to use memcpy in C:

The following program illustrates the working of the memcpy function in the C. In this program, we are copying the data of an array src to another array dst with the help of memcpy().

#include <stdio.h>
#include <string.h>

int main()
{
    //Source buffer
    char src[20] = "How Are you ?";

    //dst buffer
    char dst[20] = {0};

    //copy source buffer int dst
    memcpy(dst,src,sizeof(src));

    //printing dst buffer
    printf("dst = %s\n", dst);

    return 0;
}

Output: How Are you ?

 

Explanation:

In the above example, memcpy function is used to copy the data of src to the dst array. Because we are copying all the data of src array, so in place of n (number of bytes that you want to copy), we have used the sizeof() operator. The sizeof the operator yields size of the source array that allows us to copy all the bytes of the source to the destination buffer.

 

You can check the below video to understand the working of memcpy in C programming with example code.

 

Points should remember before using memcpy in C:

1.The memcpy() declares in the header file <string.h>.

2. The size of the destination buffer must be greater than the number of bytes you want to copy.

3. If copying takes place between objects that overlap, the behavior is undefined.

4.memcpy does not check the terminating null character, so carefully use it with strings.

5.The behavior of memcpy will be undefined if you try to access the destination and source buffer beyond their length.

6.If an array is accessed beyond the end of an object, the behavior is undefined.

7.The memcpy function does not check the validity of the destination buffer.

#include<stdio.h>
#include<string.h>

int main(void)
{

    char src[20] ="amlendra";
    char* dst;

    memcpy(dst,src,sizeof(src));

    return 0;
}

Output:

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

 

7.The memcpy() does not check the validity of the source buffer.

#include<stdio.h>
#include<string.h>

int main(void)
{
    char *src;
    char dst[12] = {0};

    memcpy(dst,src,12);

    return 0;
}

Output:

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

8.memcpy function in C works on the byte level.

9.The pointers have been declared void * for source and destination buffers so that memcpy may be used for any data type. The following program explains the working of memcpy() with different data types.

Example 1: memcpy with char type:

#include <stdio.h>
#include <string.h>
int main()
{
    //Source buffer
    char src[20] = "Hi Aticleworld";

    //dst buffer
    char dst[20] = {0};

    //copy source buffer int dst
    memcpy(dst,src,sizeof(src));

    //printing dst buffer
    printf("dst = %s\n", dst);

    return 0;
}

Output: Hi Aticleworld

Here, we have created two char arrays src[] and dest[] of sizes 20. We have then used the memcpy() function to copy all characters src[] to dest[].

 

Example 2: memcpy with integer type:

#include <stdio.h>
#include <string.h>
int main()
{
    int i = 0;
    //Source buffer
    int src[5] = {1,2,3,4,5};

    //dst buffer
    int dst[5] = {0};

    //copy source buffer int dst
    memcpy(dst,src,sizeof(src));

    for(i=0; i<5; i++)
    {
        //printing dst buffer
        printf("%d ", dst[i]);
    }

    return 0;
}

Output: 1 2 3 4 5

Here, we have created two int arrays src[] and dest[] of sizes 5. We have then used the memcpy() function to copy 5 integers src[] to dest[].

 

Example 3: memcpy with struct type:

#include <stdio.h>
#include <string.h>

struct
{
    char name[40];
    int age;
} person1, person2;

int main ()
{
    char myname[] = "Amlendra";

    //Copy name using memcpy
    memcpy ( person1.name, myname, strlen(myname)+1 );
    person1.age = 30;

    //Now copy person1 information to person2
    memcpy ( &person2, &person1, sizeof(person1) );

    printf ("person2: %s, %d \n", person2.name, person2.age );

    return 0;
}

Output:person2: Amlendra, 30

 

See this: Difference between memcpy and memmove.

 

How to implement your memcpy implementation in C?

Implementation of memcpy function in C 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 the destination one by one until n (given length).

Disclaimer: The below function is only to understand the working of memcpy. There are a lot of scenarios that are not handled in this function. You can handle the scenario as your requirement and if possible, then use the library function.

void * Memcpy(void* dst, const void* src, unsigned int cnt)
{
    char *pszDest = (char *)dst;
    const char *pszSource =( const char*)src;

    if((pszDest!= NULL) && (pszSource!= NULL))
    {
        while(cnt) //till cnt
        {
            //Copy byte by byte
            *(pszDest++)= *(pszSource++);
            --cnt;
        }
    }

    return dst;
}

 

Driver program to test the implemented memcpy in C

In the below program, the src buffer is copied into the dst buffer with the help of Memcpy.

#include <stdio.h>
#include <string.h>


void * Memcpy(void* dst, const void* src, unsigned int cnt)
{
    char *pszDest = (char *)dst;
    const char *pszSource =( const char*)src;

    if((pszDest!= NULL) && (pszSource!= NULL))
    {
        while(cnt) //till cnt
        {
            //Copy byte by byte
            *(pszDest++)= *(pszSource++);
            --cnt;
        }
    }

    return dst;
}




int main()
{

    char src[20] = "How Are you ?"; //Source String

    char dst[20] = {0}; //dst buffer

    //copy source buffer int dst
    Memcpy(dst,src,sizeof(src));

    printf("dst = %s\n", dst);

    return 0;
}

Output:

Message = How Are you?

Recommended Articles for you: