
Using memcpy Safely in C: Syntax, Examples, and Common Pitfalls
When you need to copy a fixed number of bytes in C, memcpy is a fast, widely available tool. But it copies bytes exactly as instructed: it does not check buffer sizes, add a string terminator, or handle overlapping regions. This guide covers memcpy in C, shows how to use it correctly, and explains when a different approach is safer.
What Does memcpy Do?
Declared in <string.h>, memcpy copies n bytes from a source region to a destination region. Its standard C declaration is:
void *memcpy(void *dest, const void *src, size_t n);
destpoints to the first byte of the destination region.srcpoints to the first byte of the source region.nis the number of bytes to copy.
The destination must have room for at least n bytes, and the source must provide at least n readable bytes. For a nonzero copy, both pointers must refer to valid memory regions. The function returns dest.
Unlike string functions, memcpy does not look for a null terminator. It also does not know the types or lengths of the objects you pass to it.
A Basic memcpy Example
To copy a C string into a sufficiently large array, include the terminating null character in the byte count:
#include <stdio.h>
#include <string.h>
int main(void)
{
const char src[] = "Hello, World!";
char dest[sizeof src];
memcpy(dest, src, sizeof src);
printf("Destination: %s\n", dest);
return 0;
}
Here, sizeof src includes every character in the array and its trailing '\0'. The destination has the same size, so it can hold the complete copy. Because src is an array in this scope, sizeof src gives the size of the whole array—not the size of a pointer.
When Is memcpy Appropriate?
Use memcpy when you need to copy a known number of bytes between non-overlapping, valid memory regions. Typical uses include copying byte buffers, initializing one array from another, and duplicating the object representation of a value into storage of the same type.
For example, copying a structure object into another object of the same type is valid when both objects are accessible and the regions do not overlap:
struct Point {
int x;
int y;
};
struct Point source = { 3, 7 };
struct Point destination;
memcpy(&destination, &source, sizeof source);
This copies the structure’s bytes. It does not perform a custom or recursive copy of resources referenced by the structure. If a structure contains pointers, the pointer values are copied too; the pointed-to allocations are not duplicated. That can be appropriate for some designs, but it is not a deep copy.
Overlapping Regions: Undefined Behavior
The source and destination regions passed to memcpy must not overlap. If they do, the behavior is undefined: the C standard does not specify a reliable result. A particular build may appear to work, but compiler optimizations or library implementations can change the outcome.
For example, these regions overlap because both refer to part of the same array:
char buffer[] = "Hello, World!";
/* Undefined behavior: source and destination overlap. */
memcpy(buffer + 2, buffer, 6);
Use memmove when the regions might overlap. It is designed to copy correctly in that situation. For more detail, see memcpy vs memmove.
Common memcpy Mistakes
Copying the Wrong Number of Bytes
A byte count that is too small leaves part of the intended object uncopied. A count that is too large can read beyond the source or write beyond the destination, causing undefined behavior. When copying a complete object, use its actual type or array size:
struct Data {
int a;
double b;
};
struct Data source = { 1, 2.5 };
struct Data destination;
memcpy(&destination, &source, sizeof source);
Using sizeof source avoids hard-coding a partial size such as sizeof(int). For an array, apply sizeof while the expression is still an array; when passed to a function, an array parameter is treated as a pointer, so its full size is no longer available that way.
Forgetting the String Terminator
memcpy copies only the number of bytes you request. If you copy the visible characters of a string but omit '\0', the result is not a null-terminated C string. Code that later treats it as one may read past the destination array.
For a known source array, copying sizeof src is often convenient. For a null-terminated string with a suitable destination, strlen(src) + 1 includes the terminator. Always verify that the destination has enough space. For string-specific options and their tradeoffs, see this guide to string copying.
Assuming It Checks Buffer Sizes
memcpy receives a byte count, but it cannot determine the actual capacity of either pointed-to region. It does not prevent a buffer overflow. The caller must establish that the source contains at least n bytes and the destination can hold at least n bytes before calling the function.
Expecting a Deep Copy or Type Conversion
memcpy copies bytes; it does not convert values, manage ownership, or duplicate memory behind pointers. Copying a structure with pointer members produces another set of pointer values that refer to the same targets. If those targets need independent lifetimes, write a type-aware copy routine that allocates and copies them appropriately.
Relying on Alignment or Object-Representation Assumptions
memcpy copies bytes and does not require the source or destination pointers to be aligned for a particular type. However, copying bytes into storage and then accessing that storage through an incompatible or improperly aligned typed pointer can cause problems. Prefer copying between correctly declared objects of the intended type, and follow the rules for object lifetime, effective type, and representation when working with raw storage.
Also remember that a byte-for-byte copy is not necessarily a portable way to serialize a value. Structures can contain padding, and some types can have representations that are unsuitable for comparison or transfer between different systems.
Practical Checklist
- Confirm that both memory regions are valid and large enough for the requested byte count.
- Use
memcpyonly when the regions do not overlap; usememmoveif they might. - Use
sizeofon the actual object or array when copying a complete object. - Include the null terminator when the result must be a C string.
- Handle pointer members and owned resources with type-aware logic when a shallow copy is not appropriate.
Conclusion
memcpy is useful when you need a precise byte-for-byte copy, but it is safe only when you get the memory regions and byte count right. It does not check bounds, terminate strings, or support overlapping regions; overlap makes the behavior undefined. Validate the sizes, choose memmove when overlap is possible, and use type-aware code when copying involves strings or owned resources. For concurrency concerns, see thread-safe copying: a memory-copy function alone does not synchronize shared data.
