The memcpy function from the standard library (string.h) is designed for byte-by-byte copying of memory areas from one location to another. It is a universal tool for copying arrays, structures, and other data blocks where performance is important and type conversion is not needed.
Background:
memcpy appeared with the first implementation of the standard library when there was a need to handle "raw" memory blocks, for example, for working with files, network packets, and data serialization. Similar functions are present in almost all low-level languages.
Issue:
memcpy only operates on bytes; it does not care about data types, alignment, or overlapping memory areas. Errors in size specification or incorrect areas lead to memory corruption or unexpected results. Moreover, using memcpy for overlapping areas causes undefined behavior.
Solution:
Use memcpy only if you are sure:
memmove function.Code example:
#include <string.h> typedef struct { int id; float value; } Item; Item src = {42, 3.14f}; Item dest; memcpy(&dest, &src, sizeof(Item)); // copying structure byte by byte
Key features:
Can memcpy be used to copy strings (char)?*
Yes, but only if the length is known exactly. If the string is null-terminated, strcpy or strncpy are often used. If the size is mixed up, it may lead to out-of-bounds memory access or loss of the terminating null.
char src[] = "abc"; char dest[4]; memcpy(dest, src, 4); // 3 letters + '\0' are copied
What happens when copying structures with non-standard alignment or pointers through memcpy?
memcpy does not consider semantics or internal pointers. If a structure holds dynamic fields (e.g., char *buf;), only the address itself is copied, not the contents at that address. This leads to what is known as "shallow" copying.
typedef struct { char *buf; } Wrapper; Wrapper src = {malloc(10)}; Wrapper dest; memcpy(&dest, &src, sizeof(Wrapper)); // Only pointer field, not the content
What will happen if src and dest overlap in memcpy?
The behavior is undefined by the standard, and data loss may occur. For copying with overlap, use memmove:
memmove(dest, src, size); // ensures correct copying
Arrays overlap: memcpy is applied to shift part of the array to the right, src and dest partially coincide.
Pros:
Cons:
Using memmove to handle overlapping areas, the volume of data is precisely computed as the number of bytes in the source structure.
Pros:
Cons: