Library contents

C memmove

memmove copies a byte range between regions that may overlap, making it suitable for moving the suffix of a string toward the front of the same buffer.

A simple example

memmove

  1. Start with Buffer containing xAB and its terminator
  2. Do this Shift AB and the terminator one place left
  3. Result "AB"
An overlap-safe copy lets the old and new storage regions share bytes.

Syntax

C syntax
memmove(destination, source, count)
Run this example in C

Save the program as lesson.c. Use C17 and a Unix-style shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson

Remove a prefix in an overlapping text buffer

A scanned code can start with a standard prefix that the receiving system handles separately. Test that position before extracting or moving the characters that belong to the actual identifier.

From the programchar label[] = "ID:north"
Resultnorth
lesson.c
#include <stdio.h>
#include <string.h>

int main(void) {
    char label[] = "ID:north";
    size_t skip = 3;
    memmove(label, label + skip, strlen(label + skip) + 1);
    puts(label);
    return 0;
}
Output
north

Include the terminating null byte when shifting a C string. Using memcpy for overlapping source and destination ranges has undefined behavior.

Open Group function reference for memmove

Advertisements

Shift a label one byte

A badge printer makes room for an extra prefix during a buffer edit. Copy the first three bytes one position to the right in the same buffer. Which four bytes remain at the start?

GivenABCD · copy 0–2 to 1–3
Worked resultAABC

Shift a strip of sensor data

A display moves three occupied positions over by one. Copy the first three bytes one position to the right in the same buffer. Which four bytes remain at the start?

Given1234 · copy 0–2 to 1–3
Worked result1123