memcpy_s in C

In this blog post, you will learn about the C memcpy_s() function with the help of programming examples. I will also discuss some important points related to the memcpy_s in C.

Similar to the memcpy function, the memcpy_s function also copies n characters from the source object src to the destination object dest.

Now I belive you are thinking that if C already have memcpy which copies n characters from the source object to the destination object then what is requirement to introduced memcpy_s.

Your question is genuine.  But don’t worry I will give answer of your question.

The memcpy_s is similar to the memcpy but it detect the errors at runtime. If there is a runtime-constraint violation, the memcpy_s function stores zeros in the first destmax characters of the object pointed to by dest if dest is not a null pointer and destmax is not greater than RSIZE_MAX.

 

Syntax memcpy_s in C:

The memcpy_s() declare in <string.h> header file. The following is the syntax of the memcpy_s function in C.

errno_t memcpy_s(void * restrict dest, rsize_t destmax, const void * restrict src,rsize_t n);//since C11

 

memcpy_s Parameters:

The memcpy_s() the function accepts the following parameters:

dest pointer to the destination object to copy to
desmax max number of bytes to modify in the destination
src pointer to the source object to copy from
n number of bytes to copy

 

memcpy_s return value:

The memcpy_s function returns zero if there was no runtime-constraint violation. Otherwise, a
nonzero value is returned.

 

Example program to describe how to use memcpy_s C:

The following program illustrates the working of the memcpy_s() function in the C language.

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <string.h>

int main()
{
    char dest[50] = {0};
    char src[100] = "Hi Aticleworld Readers, thanks for reading";
    int i = 0;
    const int n = 22;
    errno_t err;

    // Tell memcpy_s to copy 22 char
    err = memcpy_s(dest, sizeof(dest), src, n);
    if (err)
    {
        printf("Error executing memcpy_s.\n");
    }
    else
    {
        for (i = 0; i < n; i++)
        {
            printf("%c ", dest[i]);
        }
    }
    printf("\n");

    return 0;
}

Ouput:

Hi Aticleworld Readers

 

Note: The memcpy_s function  is only guaranteed to available to use only if the implementation defines __STDC_LIB_EXT1__ and additionally the user code defines __STDC_WANT_LIB_EXT1__ before any inclusion of <string.h>.

 

The memcpy_s() detect the following Runtime-constraints:

1. dest or src object is a null pointer.

2. destmax is greater than RSIZE_MAX.

3. n (number of character want to copy) is greater than RSIZE_MAX.

4. n is greater than destmax .

5. Copying take place between objects that overlap.

 

Recommended Post: