Compartilhar via


memcpy_s, wmemcpy_s

Copies bytes between buffers. These are versions of memcpy, wmemcpy with security enhancements as described in Security Features in the CRT.

errno_t memcpy_s(
   void *dest,
   size_t numberOfElements,
   const void *src,
   size_t count 
);
errno_t wmemcpy_s(
   wchar_t *dest,
   size_t numberOfElements,
   const wchar_t *src,
   size_t count
);

Parameters

  • dest
    New buffer.

  • numberOfElements
    Size of the destination buffer.

  • src
    Buffer to copy from.

  • count
    Number of characters to copy.

Return Value

Zero if successful; an error code on failure.

Error Conditions

dest

numberOfElements

src

Return value

Contents of dest

NULL

any

any

EINVAL

not modified

any

any

NULL

EINVAL

dest is zeroed out

any

< count

any

ERANGE

dest is zeroed out

Remarks

memcpy_s copies count bytes from src to dest; wmemcpy_s copies count wide characters (two bytes). If the source and destination overlap, the behavior of memcpy_s is undefined. Use memmove_s to handle overlapping regions.

These functions validate their parameters. If dest or src is a null pointer, or numberOfElements is too small for the buffer, these functions invoke the invalid parameter handler, as described in Parameter Validation. If execution is allowed to continue, these functions return EINVAL and set errno to EINVAL.

Requirements

Routine

Required header

memcpy_s

<memory.h> or <string.h>

wmemcpy_s

<wchar.h>

For additional compatibility information, see Compatibility in the Introduction.

Example

// crt_memcpy_s.c
// Copy memory in a more secure way.

#include <memory.h>
#include <stdio.h>

int main()
{
   int a1[10], a2[100], i;
   errno_t err;

   // Populate a2 with squares of integers
   for (i = 0; i < 100; i++)
   {
      a2[i] = i*i;
   }

   // Tell memcpy_s to copy 10 ints (40 bytes), giving
   // the size of the a1 array (also 40 bytes).
   err = memcpy_s(a1, sizeof(a1), a2, 10 * sizeof (int) );    
   if (err)
   {
      printf("Error executing memcpy_s.\n");
   }
   else
   {
     for (i = 0; i < 10; i++)
       printf("%d ", a1[i]);
   }
   printf("\n");
}
0 1 4 9 16 25 36 49 64 81 

.NET Framework Equivalent

Not applicable. To call the standard C function, use PInvoke. For more information, see Platform Invoke Examples.

See Also

Reference

Buffer Manipulation

_memccpy

memchr, wmemchr

memcmp, wmemcmp

memmove, wmemmove

memset, wmemset

strcpy, wcscpy, _mbscpy

strncpy, _strncpy_l, wcsncpy, _wcsncpy_l, _mbsncpy, _mbsncpy_l

strncpy_s, _strncpy_s_l, wcsncpy_s, _wcsncpy_s_l, _mbsncpy_s, _mbsncpy_s_l