memcpy in C copies n bytes from a source buffer to a destination buffer and returns a pointer to the destination. The two buffers must not overlap; if they might, use memmove instead.
#include <string.h>
void *memcpy(void *restrict dest, const void *restrict src, size_t n);
The function lives in <string.h>. The restrict qualifiers on both pointers were added in C99 and are the reason overlap is forbidden, as explained below.
How memcpy works
According to the Linux man-pages, memcpy() copies n bytes from the memory area src to the memory area dest, and returns a pointer to dest. The C reference describes both objects as being interpreted as arrays of unsigned char. In practice that means memcpy has no idea what the data is. It does not look at types, it does not stop at a zero byte, and it does not check that either buffer is big enough. You supply the byte count, and the function trusts it.
That makes it the right tool for copying raw blocks of memory: arrays of integers, plain structs that hold no pointers, or a chunk of a binary buffer. It is the wrong tool for anything where you want the function to decide the length, such as copying a string of unknown size.
A basic memcpy example
Copy an array of five integers into another array of the same size. Use sizeof on the array so the byte count follows the element type automatically.
#include <stdio.h>
#include <string.h>
int main(void)
{
int source[5] = {10, 20, 30, 40, 50};
int copy[5];
memcpy(copy, source, sizeof source);
for (size_t i = 0; i < 5; i++) {
printf("%d ", copy[i]);
}
printf("\n");
return 0;
}
Example output:
10 20 30 40 50
sizeof source is 5 times sizeof(int). On a platform where int is 4 bytes, that is 20 bytes. Writing a literal 5 as the count would copy only 5 bytes, which is a classic mistake: the count is in bytes, not elements.
The sizeof trick only works on a real array in the same scope. If the array was passed to a function, it has already decayed to a pointer, and sizeof returns the size of the pointer. Pass the element count as a separate parameter and multiply: count * sizeof *destination. See pointers in C for why that happens.
Copying a string with memcpy
A C string ends with a null byte, and memcpy will not add one for you. Include it in the count:
const char *text = "hello";
char buffer[16];
memcpy(buffer, text, strlen(text) + 1);
Here strlen("hello") is 5, so the count is 6 and the terminator is copied too. Leave off the + 1 and buffer holds the five letters followed by whatever was already in memory, so printing it is undefined. Also make sure the destination is large enough: the 16-byte buffer above is fine for 6 bytes, but memcpy will happily write past the end of a smaller one.
memcpy vs memmove: the overlap rule
The man page for memcpy says plainly that the memory areas must not overlap, and points to memmove(3) for overlapping areas. The C reference adds the reason: overlap violates the restrict contract, so the behavior is undefined. restrict is a promise to the compiler that the two pointers refer to separate memory, and the compiler is free to optimize on that assumption.
memmove has the signature void *memmove(void *dest, const void *src, size_t n); and, per its man page, the memory areas may overlap. The C reference says it "must take precautions to handle overlapping inputs". Overlap happens more often than it sounds. Shifting the contents of an array by one slot is the standard case:
int values[6] = {1, 2, 3, 4, 5, 0};
/* make room at index 0: move the first 5 elements one slot right */
memmove(&values[1], &values[0], 5 * sizeof values[0]);
values[0] = 99;
Example result: values is now {99, 1, 2, 3, 4, 5}. The source range (indexes 0 to 4) and the destination range (indexes 1 to 5) share indexes 1 to 4, so this is overlap. Calling memcpy here is undefined behavior, even if it happens to give the right answer on your machine today.
| memcpy | memmove | |
|---|---|---|
| Header | <string.h> | <string.h> |
| Overlapping regions | Undefined behavior | Allowed and handled |
| Pointer qualifiers | restrict on both (C99) | None |
| Return value | Pointer to dest | Pointer to dest |
| Checks buffer size | No | No |
Neither function checks sizes. Only the overlap behavior differs.
A real-world case where overlap broke programs
The man page records an example. In glibc 2.13, an optimization changed the order in which memcpy copies bytes on some platforms, including x86-64. Programs that had overlapped their buffers and relied on the old copy order stopped working. glibc 2.14 added a versioned symbol so that binaries linked against older glibc versions get an older memcpy that aliases memmove. The lesson is that "it worked before" is not evidence that overlapping memcpy is safe. A library update or a different compiler can change the result.
Safe-use checklist
- Size the destination first. The destination must hold at least
nbytes.memcpyperforms no check, so a count that is too large overwrites adjacent memory. - Count in bytes. Multiply the element count by
sizeofthe element type. - Do not copy more than the source has. Reading past the end of the source is also undefined.
- Use
memmovewhen in doubt about overlap. Copying within one array is the usual trigger. - Do not pass null pointers. The C reference says the behavior is undefined if either pointer is invalid or null, and it states no exception for a count of 0. Check pointers before calling when the count can be zero.
- Do not use it on objects that own pointers unless a shallow copy is what you want. A struct containing a
char *copied withmemcpygets a second pointer to the same memory, not a second string. Freeing both causes a double free. If the memory came frommalloc, see malloc in C.
Is there a safer memcpy: memcpy_s
C11 Annex K defines memcpy_s(dest, destsz, src, count). At runtime it detects null pointers, counts above RSIZE_MAX, a count greater than destsz, and overlapping objects. On error it zeroes the destination range (if the destination and destsz are valid), calls the installed constraint handler, and returns a non-zero value; on success it returns zero.
It has two practical problems. It is optional: per the C reference, it is only guaranteed to exist if the implementation defines __STDC_LIB_EXT1__ and you define __STDC_WANT_LIB_EXT1__ as 1 before including <string.h>. And the reference notes it cannot catch a wrong destsz: if you pass a size larger than the real buffer, the overflow goes undetected. For portable code, the dependable approach is still to compute and validate the sizes yourself before calling memcpy.
if (destination == NULL || source == NULL) {
return -1;
}
if (count > destination_capacity) {
return -1;
}
memcpy(destination, source, count);
This pattern keeps the checks next to the call, so the next reader can see why the copy is safe.
If the copy gives wrong results
If the copied string prints garbage at the end, the terminating null byte was not included in the count. If the program crashes or other variables change value after a copy, check that the destination capacity is at least n bytes and that the count was not computed from a pointer's sizeof. If shifting array elements gives repeated values, you are probably overlapping with memcpy; switch to memmove.
Frequently asked questions
- What is the difference between memcpy and memmove in C?
- Both copy n bytes from a source to a destination. memcpy requires that the two regions do not overlap, and overlapping them is undefined behavior. memmove accepts overlapping regions and handles them correctly. If you are unsure whether the regions can overlap, use memmove.
- What does memcpy return?
- memcpy returns a pointer to the destination buffer, the same value you passed as the first argument. Most code ignores it, but it lets you chain calls or assign the result directly.
- Does memcpy stop at a null terminator?
- No. memcpy copies exactly n bytes and treats the data as raw bytes, so a zero byte has no special meaning. If you copy a string with it, you must include the terminating null byte in the count, for example by using strlen(text) + 1.
- Is memcpy with a size of 0 safe?
- Be careful. The C reference states that the behavior is undefined if either pointer is invalid or null, and it gives no exception for a size of 0. Guard against null pointers before calling, even when the count may be zero.
- Is there a bounds-checked version of memcpy?
- C11 Annex K defines memcpy_s, which checks for null pointers, oversized counts and overlap at runtime. It is optional: it is only guaranteed to be available if the implementation defines __STDC_LIB_EXT1__ and you define __STDC_WANT_LIB_EXT1__ as 1 before including string.h. Many common compilers and libraries do not provide it.