memcpy() / memmove() / memset() / memcmp()
Functions that copy, initialize, and compare memory blocks byte by byte. They can directly manipulate memory of any data type, not just strings.
Syntax
// Copies n bytes from src to dst (memory regions must not overlap). // Return value: pointer to dst. void *memcpy(void *dst, const void *src, size_t n); // Copies n bytes from src to dst (safe even if memory regions overlap). void *memmove(void *dst, const void *src, size_t n); // Fills the first n bytes of s with the value c (0–255). void *memset(void *s, int c, size_t n); // Compares the first n bytes of s1 and s2. // Return value: negative if s1 < s2, 0 if equal, positive if s1 > s2. int memcmp(const void *s1, const void *s2, size_t n);
Function Comparison
| Function | Purpose | Overlapping Regions | Description |
|---|---|---|---|
| memcpy() | Copy | Not allowed | A fast copy. Use memmove() if src and dst may overlap. |
| memmove() | Copy | Allowed | A safe copy that handles overlapping regions. May be slightly slower than memcpy(). |
| memset() | Initialize | — | Fills an entire buffer with zero or a specific byte value. |
| memcmp() | Compare | — | Used for equality comparison of binary data. Useful for non-string data. |
Sample Code
#include <stdio.h>
#include <string.h>
typedef struct { int x; int y; } Point;
int main(void) {
// Copy a struct with memcpy.
Point p1 = {10, 20};
Point p2;
memcpy(&p2, &p1, sizeof(Point));
printf("p2: x=%d, y=%d\n", p2.x, p2.y); // Outputs: p2: x=10, y=20
// Initialize a buffer to zero with memset.
int arr[5];
memset(arr, 0, sizeof(arr));
printf("arr[0]=%d, arr[4]=%d\n", arr[0], arr[4]); // All elements are 0.
// Fill an array with a specific byte value using memset (note: byte-level fill).
unsigned char buf[4];
memset(buf, 0xFF, sizeof(buf));
printf("buf: %02X %02X %02X %02X\n", buf[0], buf[1], buf[2], buf[3]);
// Outputs: FF FF FF FF
// Safely shift overlapping memory with memmove.
char s[] = "hello world";
memmove(s, s + 6, 5); // Move "world" to the beginning.
s[5] = '\0';
printf("after memmove: %s\n", s); // Outputs: after memmove: world
// Compare binary data with memcmp.
char a[] = {1, 2, 3};
char b[] = {1, 2, 3};
printf("memcmp: %d\n", memcmp(a, b, 3)); // Outputs: memcmp: 0 (equal)
return 0;
}
Notes
If the source and destination of memcpy() overlap, the behavior is undefined. Always use memmove() when shifting data within the same buffer.
When using memset() to initialize an int array to a non-zero value, keep in mind that the fill is done byte by byte, so the result may not be the value you expect. For example, memset(arr, 1, sizeof(arr)) sets each element to 0x01010101 (in hex). Initializing to integer zero (0x00000000) works correctly.
For zero-initialization immediately after dynamic allocation, using calloc() is more concise. See 'malloc() / free()' for details.
If you find any errors or copyright issues, please contact us.