memcpy_s, wmemcpy_s

 

The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at 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 destSize,  
   const void *src,  
   size_t count   
);  
errno_t wmemcpy_s(  
   wchar_t *dest,  
   size_t destSize,  
   const wchar_t *src,  
   size_t count  
);  

Parameters

dest
New buffer.

destSize
Size of the destination buffer, in bytes for memcpy_s and wide characters (wchar_t) for wmemcpy_s.

src
Buffer to copy from.

count
Number of characters to copy.

Zero if successful; an error code on failure.

Error Conditions

destdestSizesrccountReturn valueContents of dest
anyanyany00Not modified
NULLanyanynon-zeroEINVALNot modified
anyanyNULLnon-zeroEINVALdest is zeroed out
any< countanynon-zeroERANGEdest is zeroed out

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 count is non-zero and dest or src is a null pointer, or destSize is smaller than count, 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.

RoutineRequired header
memcpy_s<memory.h> or <string.h>
wmemcpy_s<wchar.h>

For additional compatibility information, see Compatibility in the Introduction.

// 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   

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

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

Show: