C memcpy() Function Explained with Examples (Beginner Friendly)

Hello, this is BlockDMask.

Today, we will learn how to use the memcpy() function in C/C++ to copy memory contents from one place to another.

Now, let’s dive into how memcpy() works, with practical examples and some important things to watch out for.

Table of Contents



✅ 1. What is memcpy()?

The function name memcpy comes from "memory copy". As the name suggests, it copies a block of memory from a source to a destination in raw bytes.

Header files: In C: <string.h> In C++: <cstring>

Function prototype:

void* memcpy(void* dest, const void* source, size_t num);

Parameters:

  • dest: Pointer to the destination memory block
  • source: Pointer to the source memory block
  • num: Number of bytes to copy

In short, memcpy(dest, source, num) copies num bytes from source to dest.

⚠ Important 1: If you copy C-style strings (char*), remember that null-termination \0 is not automatically handled. If you want to copy the full string, you must copy string length + 1 to include \0.

⚠ Important 2: If your source and destination memory blocks overlap, memcpy() may not work correctly. In that case, use memmove() instead to safely handle overlapping regions.



✅ 2. memcpy example with int array

Let’s start with a simple example using integer arrays:

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

int main(void)
{
    int source[] = { 10, 20, 30 };
    int target[3];

    // Copy memory block
    memcpy(target, source, sizeof(int) * 3);

    printf("source: ");
    for (int i = 0; i < 3; i++)
        printf("%d ", source[i]);
    printf("\n");

    printf("target: ");
    for (int i = 0; i < 3; i++)
        printf("%d ", target[i]);

    return 0;
}

Output:

source: 10 20 30
target: 10 20 30

The values from source were successfully copied into target using memcpy().



✅ 3. memcpy example with partial string copy

Now let’s try copying only a part of a string.

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

int main(void)
{
    const char* source = "HelloWorld";
    char target[] = "abcdefghijklmno";

    // Copy first 5 characters only
    memcpy(target, source, sizeof(char) * 5);

    printf("source: %s\n", source);
    printf("target: %s\n", target);

    return 0;
}

Output:

source: HelloWorld
target: Hellofghijklmno

Only the first 5 characters Hello are copied into target. The rest of the string remains unchanged from the original target contents.



✅ 4. memcpy example with full string copy (critical point)

This is where many beginners make mistakes when copying full strings.

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

int main(void)
{
    char source[] = "BlockDMask";
    char target1[] = "abcdefghijklmno";
    char target2[] = "abcdefghijklmno";

    // Without copying null terminator
    memcpy(target1, source, sizeof(char) * 10);

    // Copying null terminator (\0)
    memcpy(target2, source, sizeof(char) * 10 + 1);

    printf("source : %s\n", source);
    printf("target1: %s\n", target1);
    printf("target2: %s\n", target2);

    return 0;
}

Output:

source : BlockDMask
target1: BlockDMaskklmno
target2: BlockDMask

Explanation:

  • target1 doesn’t include the null terminator \0. So the string doesn’t properly terminate and prints leftover garbage values.
  • target2 includes the null terminator. The string is copied correctly.

Always remember: For full string copy, you must include +1 to cover the null terminator!

In memory:

  • target1: BlockDMaskklmno\0
  • target2: BlockDMask\0klmno\0

This behavior is a classic beginner’s trap in C string handling.



✅ 5. Extra example: memcpy with struct (structure copy)

memcpy is not only for arrays — you can copy entire structs as well:

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

typedef struct {
    int id;
    float score;
} Student;

int main(void)
{
    Student s1 = {1001, 93.5};
    Student s2;

    memcpy(&s2, &s1, sizeof(Student));

    printf("s1: id=%d, score=%.1f\n", s1.id, s1.score);
    printf("s2: id=%d, score=%.1f\n", s2.id, s2.score);

    return 0;
}

Output:

s1: id=1001, score=93.5
s2: id=1001, score=93.5

We successfully copied the entire struct using memcpy(). ⚠ However, be careful when structs contain pointers — memcpy works best for shallow copies.



That’s everything you need to know about memcpy() function in C/C++, along with common pitfalls and practical examples.
Thank you for reading!

Comments

Popular posts from this blog

Python split() Function: Usage and Examples

Privacy Policy for Android Apps

How to Write Comments in Python (Single-line, Multi-line, Shortcuts & Indentation Tips)