Open In App

memcpy() in C

Last Updated : 01 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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>  // For memcpy

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
// C program to demonstrate working of memcpy
#include <stdio.h>
#include <string.h>

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

    // Copies contents of str2 to str1
    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.


  1. memcpy() leads to undefined behaviour when source and destination addresses overlap as it does not handles overlapping memory regions.
  2. The memcpy() function simply copies bytes without initialising any memory.
  3. 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.
  4. memcpy() only copies the pointer values (i.e., the addresses they hold), not the actual objects or data those pointers reference.

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


Next Article
Article Tags :
Practice Tags :

Similar Reads