Reading history

C memcpy, memmove and memset

7 min read 3 views

Copy, move, fill, compare and search memory in C with memcpy, memmove, memset, memcmp and memchr, and avoid their common traps.

String functions like strcpy stop at the first '\0', so they only work on text. To copy, fill, move or compare any block of memory, such as an array of numbers, a struct or raw file data, C gives you the mem functions in <string.h>. They work byte by byte and are among the fastest functions in the standard library. This lesson covers memcpy, memmove, memset, memcmp and memchr.

In this lesson you will learn

  • Copying blocks with memcpy
  • Why overlapping copies need memmove
  • Filling memory with memset, and its common trap
  • Comparing and searching with memcmp and memchr
  • Inserting and removing array items with memmove

You should know pointers, string functions and sizeof.

The Five mem Functions

#include <stdio.h>
#include <string.h>

struct Point { int x, y; };

static void show(const char *label, const int *a, size_t n) {
    printf("%-22s", label);
    for (size_t i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");
}

int main(void) {
    int src[6] = {1, 2, 3, 4, 5, 6};
    int dst[6];

    /* memcpy: copy bytes from one place to another (no overlap allowed) */
    memcpy(dst, src, sizeof src);
    show("memcpy whole array:", dst, 6);

    /* memset: fill bytes. Safe for 0, or for char arrays */
    memset(dst, 0, sizeof dst);
    show("memset to 0:", dst, 6);

    char line[11];
    memset(line, '=', 10);
    line[10] = '\0';
    printf("memset chars:         %s\n", line);

    /* memset sets BYTES, so 1 does not give the int 1 */
    int ones[3];
    memset(ones, 1, sizeof ones);
    printf("memset ints to 1:     %d %d %d  (0x%x)\n", ones[0], ones[1], ones[2], (unsigned)ones[0]);

    /* memmove: like memcpy but safe when the regions overlap */
    int a[8] = {1, 2, 3, 4, 5, 6, 7, 8};
    memmove(a + 2, a, 4 * sizeof a[0]);       /* shift first 4 right by 2 */
    show("memmove shift right:", a, 8);

    /* memcmp: compare bytes, returns <0, 0 or >0 like strcmp */
    struct Point p = {3, 4}, q = {3, 4}, r = {3, 5};
    printf("memcmp p,q = %d   p,r < 0? %s\n", memcmp(&p, &q, sizeof p),
           memcmp(&p, &r, sizeof p) < 0 ? "yes" : "no");

    /* Copy a struct with memcpy (plain assignment does the same) */
    struct Point copy;
    memcpy(&copy, &r, sizeof copy);
    printf("copied point = (%d, %d)\n", copy.x, copy.y);
    return 0;
}

Output

memcpy whole array:   1 2 3 4 5 6 
memset to 0:          0 0 0 0 0 0 
memset chars:         ==========
memset ints to 1:     16843009 16843009 16843009  (0x1010101)
memmove shift right:  1 2 1 2 3 4 7 8 
memcmp p,q = 0   p,r < 0? yes
copied point = (3, 5)
  • memcpy(dst, src, n) copies n bytes. Always give sizes in bytes, usually with sizeof: sizeof src is the whole array, 24 bytes here.
  • memset(p, value, n) sets n bytes to value. It is safe for clearing anything to zero and for filling char arrays.
  • The trap: memset(ones, 1, sizeof ones) sets every byte to 1, so each 4-byte int becomes 0x01010101 = 16,843,009, not 1. Use a loop to set ints to a non-zero value.
  • memmove copies correctly even when source and destination overlap. Shifting the first four items right by two worked: 1 2 1 2 3 4 7 8.
  • memcmp compares bytes and returns a negative number, zero or a positive number, like strcmp. It does not stop at '\0'.

Careful with memcmp on structs

Structs can contain hidden padding bytes with random contents. Two structs with equal fields may then compare as different. struct Point here has no padding, but in general compare structs field by field.

memcpy vs memmove

Imagine copying 4 items one place to the right inside the same array. If you copy from the front, the first copy overwrites an item you have not read yet. memcpy assumes the regions do not overlap, so it may copy in that unsafe order, and the C standard says the result is undefined. memmove checks the direction and copies from the back when needed.

memcpymemmove
Regions may overlap?No (undefined behaviour)Yes
SpeedSlightly fasterNearly as fast
Use forCopying between separate buffersShifting data inside one buffer

Inserting, Removing and Building Buffers

#include <stdio.h>
#include <string.h>

/* Remove element i from an array of n ints by sliding the rest left */
static size_t remove_at(int *a, size_t n, size_t i) {
    memmove(&a[i], &a[i + 1], (n - i - 1) * sizeof a[0]);
    return n - 1;
}

/* Insert value at position i (array must have room for n + 1) */
static size_t insert_at(int *a, size_t n, size_t i, int value) {
    memmove(&a[i + 1], &a[i], (n - i) * sizeof a[0]);
    a[i] = value;
    return n + 1;
}

static void print(const int *a, size_t n) {
    for (size_t i = 0; i < n; i++) printf("%d ", a[i]);
    printf("(n=%zu)\n", n);
}

int main(void) {
    int a[10] = {10, 20, 30, 40, 50};
    size_t n = 5;
    print(a, n);
    n = insert_at(a, n, 2, 25);   print(a, n);
    n = insert_at(a, n, 0, 5);    print(a, n);
    n = remove_at(a, n, 3);       print(a, n);

    /* memchr: find a byte in a block of memory */
    const char data[] = "ID:4471;NAME:Rafi";
    const char *semi = memchr(data, ';', sizeof data);
    if (semi)
        printf("';' found at index %td, name part = %s\n", semi - data, semi + 1);

    /* memcpy into a buffer piece by piece */
    char packet[32];
    size_t pos = 0;
    const char *parts[] = {"HDR", "|", "PAYLOAD", "|", "END"};
    for (size_t i = 0; i < 5; i++) {
        size_t len = strlen(parts[i]);
        memcpy(packet + pos, parts[i], len);
        pos += len;
    }
    packet[pos] = '\0';
    printf("packet = %s (%zu bytes)\n", packet, pos);
    return 0;
}

Output

10 20 30 40 50 (n=5)
10 20 25 30 40 50 (n=6)
5 10 20 25 30 40 50 (n=7)
5 10 20 30 40 50 (n=6)
';' found at index 7, name part = NAME:Rafi
packet = HDR|PAYLOAD|END (15 bytes)
  • insert_at slides every item from position i one place to the right to make a gap, then writes the new value. Source and destination overlap, so it must be memmove.
  • remove_at slides the items after i one place to the left, covering the removed item.
  • The byte count is always number of items × size of one item.
  • memchr finds the first byte with a given value inside a block of known length and returns a pointer to it, or NULL. Subtracting two pointers gives the position, printed with %td.
  • Building a packet with memcpy and a running position is a common pattern for network and file data. The code adds the '\0' itself at the end, because memcpy never adds one.

Common Mistakes

  1. Passing an item count instead of a byte count: memcpy(dst, src, 5) copies 5 bytes, not 5 ints. Write 5 * sizeof *src.
  2. Using sizeof on a pointer. Inside a function, sizeof arr of a pointer parameter gives 8, not the array size. Pass the size in.
  3. Using memcpy on overlapping memory. Use memmove.
  4. Setting non-zero ints or doubles with memset. Only 0 (and −1 for ints, where every byte is 0xFF) give the value you expect.

Practice Exercises

Exercise 1. Copy the last 3 items of int a[8] into a new array int b[3] with one call.

Show answer
int a[8] = {1, 2, 3, 4, 5, 6, 7, 8};
int b[3];
memcpy(b, a + 5, 3 * sizeof a[0]);   /* b = 6 7 8 */

Exercise 2. Write a function that rotates an int array left by one place (the first item moves to the end).

Show answer
void rotate_left(int *a, size_t n) {
    if (n < 2) return;
    int first = a[0];
    memmove(a, a + 1, (n - 1) * sizeof a[0]);
    a[n - 1] = first;
}
/* {1, 2, 3, 4} becomes {2, 3, 4, 1} */

Frequently Asked Questions

Is memcpy faster than a for loop?

Usually yes, for anything but tiny copies. Library versions copy many bytes at a time using special CPU instructions. Modern compilers also turn simple copy loops into memcpy calls automatically.

Can I use memset to clear a struct?

Yes, memset(&s, 0, sizeof s) is common, and it also clears the padding. For a new variable, struct Point p = {0}; is simpler and sets every field to zero.

Summary

  • memcpy copies bytes between separate blocks; memmove handles overlap.
  • memset fills bytes, which is right for zero and for chars but not for other int values.
  • memcmp compares and memchr searches a block of known length.
  • Sizes are always in bytes: count × sizeof one item.

Next: C Binary Files: fseek, ftell and Random Access.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *