memcpy() in C

Last Updated : 22 Sep, 2025

The memcpy() function in C is defined in the <string.h> header is a part of the standard library in C. The memcpy() function is used to copy a block of memory from one location to another.

Example:

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

int main() {

    // Initialize a variable
    int a = 20;
    int b = 10;
    
    printf("Value of b before calling memcpy: %d\n", b);

    // Use memcpy to copy the value of 'a' into 'b'
    memcpy(&b, &a, sizeof(int)); 

    printf("Value of b after calling memcpy: %d\n", b);

    return 0;
}

Output
Value of b before calling memcpy: 10
Value of b after calling memcpy: 20

memcpy() Function

The memcpy function in C copies the specified number of bytes from one memory location to another memory location regardless of the type of data stored. Where both source and destination are raw memory addresses. The memcpy() function is optimized for copying memory chunks in an efficient manner and it copies memory in a byte-by-byte format.

Syntax

C++
memcpy(*to, *from, numBytes);

Parameters

  • to: A pointer to the memory location where the copied data will be stored.
  • from: A pointer to the memory location from where the data is to be copied.
  • numBytes: The number of bytes to be copied.

Return Value

  • This function returns a pointer to the memory location where data is copied.

Copying String using memcpy() in C

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

int main() {
    char str1[] = "Geeks";
    char str2[6] = "";

    // Copies contents of str1 to str2
    memcpy(str2, str1, sizeof(str1));

    printf("str2 after memcpy:");
    printf("%s",str2);

    return 0;
}

Output
str2 after memcpy:Geeks

Important Points about memcpy() in C

  1. memcpy() function copies the memory in a byte-by-byte format without any checks or transformations, meaning it does not handle type conversions or alignment issues, check for overflow or \0.
  2. memcpy() leads to undefined behaviour when source and destination addresses overlap as it does not handles overlapping memory regions.
  3. The memcpy() function simply copies bytes without initialising any memory.
  4. The memcpy() function makes a shallow copy as it only copies the raw bytes of the memory from one location to another. It does not perform a deep copy or handle objects at a higher level.
  5. memcpy() copies the actual bytes of the memory you specify. If you pass it a pointer variable, it copies the pointer’s value (the address). If you pass it the memory the pointer points to, it copies the data at that memory, not just the pointer

Note: memmove() is another library function that handles overlapping well.

Comment