Blog Datasheets Home About me Clients My work Services Contact

G2Labs Grzegorz Grzęda

The memcpy() function in C: A beginner's guide

June 29, 2023

The memcpy() Function in C: A Beginner’s Guide

In C programming, the memcpy() function is a fundamental part of the standard library that enables you to copy a specified number of bytes from one memory location to another. This guide will explain its purpose and demonstrate how to use it with examples.

Function Parameters and Return Value

memcpy() takes the following three parameters:

  1. dst: The pointer to the destination buffer where you want to copy the data.

  2. src: The pointer to the source buffer from where the data will be copied. This is marked as const, indicating that the original data will not be altered during the copying process.

  3. num: The number of bytes to be copied from the source to the destination.

After copying, memcpy() returns a pointer to the destination buffer, dst.

Basic Example

Consider the following example to understand how memcpy() works:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <string.h> // Required for memcpy

int main() {
    const char *src = "Hello, World!";
    char dst[50];

    // Copy 13 bytes from src to dst
    memcpy(dst, src, 13);
    // dst now contains "Hello, World!" followed by uninitialized data

    return 0;
}

In this code snippet, we copy the string “Hello, World!” from the source to the destination buffer, ensuring dst is large enough to hold the copied data.

Extending the Examples

Let’s extend our examples to include various use cases and explore some corner cases:

Copying an Array of Integers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <string.h> // Required for memcpy

int main() {
    int src[] = {1, 2, 3, 4, 5};
    int dst[5];

    // Copy entire array
    memcpy(dst, src, sizeof(src));
    // dst now contains {1, 2, 3, 4, 5}

    return 0;
}

Handling Overlapping Memory Regions

It’s important to note that memcpy() should not be used when source and destination memory blocks overlap. For such cases, use memmove() instead.

Copying a Structure

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <string.h> // Required for memcpy

struct MyStruct {
    int id;
    float value;
    char name[20];
};

int main() {
    struct MyStruct src = {1, 3.14, "StructName"};
    struct MyStruct dst;

    // Copy the structure
    memcpy(&dst, &src, sizeof(struct MyStruct));
    // dst now has the same content as src

    return 0;
}

Corner Case: Insufficient Destination Size

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#include <string.h> // Required for memcpy

int main() {
    const char *src = "Data too large";
    char dst[10];

    // Attempting to copy more bytes than the destination can hold
    // This will lead to undefined behavior, likely overwriting memory
    memcpy(dst, src, 15);
    // dst buffer overflows, program might crash or behave unexpectedly

    return 0;
}

In this dangerous example, we attempt to copy more data into dst than it can hold, which leads to undefined behavior and potential memory corruption.

Custom Implementation

While you can implement your own version of memcpy(), like the one provided, it is highly recommended to use the version from the standard library <string.h>, as it is optimized for performance and safety.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
void *my_memcpy(void *dst, const void *src, size_t num) {
    char *d = dst;
    const char *s = src;
    
    while (num--) {
        *d++ = *s++;
    }

    return dst;
}

Always remember to use memcpy() carefully, ensuring that you are copying the appropriate number of bytes and that there is no overlap between the source and destination memory blocks. By understanding and using memcpy() correctly, you can handle data in your C programs with confidence and precision.


➡️ Understanding the memset() function in C


⬅️ Testing strategies for clean code in C and Python


Go back to Posts.