memcpy(3)

C library function

Copies n bytes from one memory area to another and returns the destination. The two areas must not overlap, or the result is undefined.

Synopsis
#include <string.h>
void *memcpy(void *restrict dest, const void *restrict src, size_t n);

Description

memcpy copies n raw bytes from src to dest. It copies bytes, not a string: it stops at no '\0' and copies exactly the number you ask for. That is what makes it useful for structures, arrays and any other memory area, not just text.

The constraint to remember is in the signature: the restrict on both pointers tells the compiler that the areas do not overlap. The C23 standard is blunt about it: “If copying takes place between objects that overlap, the behavior is undefined”. If your areas can overlap, for example when you shift data inside one array, use memmove(3).

Return value

memcpy returns dest, the destination address you passed it. The value is rarely used; it lets you chain calls.

Example

memcpy.c
#include <stdio.h>#include <string.h>
int main(void){    char src[] = "git push";    char dst[16];
    memcpy(dst, src, sizeof(src));   /* sizeof includes the '\0' */    printf("%s\n", dst);    return 0;}
Terminal
$ gcc -Wall -Wextra -g memcpy.c -o memcpy$ ./memcpygit push

Pitfalls

  • Copying a string without its '\0': memcpy does not add one. Copy strlen(src) + 1 bytes, or use sizeof on an array.

  • Forgetting that dest must be large enough for n bytes: an overflow does not always crash, but it is a bug that Valgrind catches.

  • Using it on areas that overlap: the result is undefined, and that case is the job of memmove.

C

memcpy

Write gm_memcpy, which copies exactly n bytes one at a time and does not stop at a null byte the way a string copy would.

Open the exercise

Now write it yourself.