FROMDEV

Thread-Safe Memory Copy in C and C++

Thread-Safe Memory Copy in C and C++

How to Copy Shared Memory Safely in C and C++

Copying bytes is easy; coordinating the threads that access those bytes is the hard part. In C and C++, memcpy does not make shared data thread-safe. A safe copy requires a clear ownership or synchronization rule that protects the source and destination for the entire period they are accessed.

This guide explains when ordinary memory-copy functions are appropriate, how to protect shared buffers with a mutex, and which common mistakes can still cause data races or undefined behavior.

What Does Thread-Safe Memory Copy Mean?

A memory-copy operation is safe in a multithreaded program only when concurrent access cannot create a data race or invalidate the memory being copied. The standard C and C++ functions memcpy and memmove copy bytes; neither function provides synchronization.

For example, if one thread calls memcpy while another thread modifies the same source bytes without synchronization, the program has a data race. In C and C++, a data race on ordinary, non-atomic objects results in undefined behavior. Locking only the copying thread is not enough: every thread that reads or writes the protected data must follow the same locking protocol.

Choose the Right Copy Function

Use memcpy when the source and destination regions do not overlap. If they overlap, use memmove, which is specified to handle overlapping regions. Neither function protects memory from concurrent changes or makes an invalid pointer safe.

For a closer look at overlap behavior, read How memmove Handles Overlapping Memory Regions. Before copying dynamically allocated buffers, also confirm their sizes and lifetimes; this overview of Malloc vs Calloc: Understanding the Memory Allocation Twins can help clarify allocation basics.

Protect Shared Buffers with a Mutex

A mutex works when all threads that access a shared buffer use the same mutex. Keep the lock held while reading the source and writing the destination. In C++, use RAII locking so the mutex is released even if the function exits early or an exception is thrown.

C++ Example: Copying Under a Lock

#include <algorithm>
#include <cstddef>
#include <cstring>
#include <mutex>
#include <vector>

std::mutex buffer_mutex;
std::vector<unsigned char> shared_buffer;

bool copy_buffer(std::vector<unsigned char>& destination)
{
    std::lock_guard<std::mutex> lock(buffer_mutex);
    destination.resize(shared_buffer.size());

    if (!shared_buffer.empty()) {
        std::memcpy(destination.data(),
                    shared_buffer.data(),
                    shared_buffer.size());
    }
    return true;
}

The lock protects the shared source while its size and contents are read. The destination in this example is assumed to be private to the calling thread. If other threads access or modify that destination, they need their own compatible synchronization. For a fixed-size buffer, validate its capacity before copying; for dynamic containers, make sure allocation and resizing happen under the appropriate ownership or lock policy.

C Example: Mutex-Protected Copy

In C, the C11 threads library provides mtx_t when supported by the implementation. The mutex must be initialized before use, and all access to the shared source must follow the same locking rule.

#include <string.h>
#include <threads.h>

static mtx_t buffer_mutex;
static unsigned char shared_buffer[256];
static size_t shared_length;

int initialize_buffer_mutex(void)
{
    return mtx_init(&buffer_mutex, mtx_plain) == thrd_success;
}

int copy_shared_buffer(unsigned char *destination, size_t capacity,
                       size_t *copied)
{
    if (destination == NULL || copied == NULL)
        return 0;

    if (mtx_lock(&buffer_mutex) != thrd_success)
        return 0;

    if (shared_length > capacity) {
        mtx_unlock(&buffer_mutex);
        return 0;
    }

    memcpy(destination, shared_buffer, shared_length);
    *copied = shared_length;

    mtx_unlock(&buffer_mutex);
    return 1;
}

This example assumes the shared buffer and its length are updated only while holding buffer_mutex. In production code, check mutex initialization and unlock results as appropriate for the application, and destroy the mutex only after no thread can use it. C11 thread support is optional on some platforms; use the platform’s supported threading API if necessary.

Memory Safety Checks That Matter

Synchronization prevents conflicting access only when used consistently. It does not verify pointer validity, buffer capacity, or allocation lifetime. Before copying, make sure that:

A common error is releasing the mutex immediately after obtaining a pointer to shared data, then copying through that pointer. Another thread could change or free the memory after the lock is released. Keep the lock for the whole access, or create a valid independent snapshot while the data is protected.

Performance and Design Considerations

Mutexes add coordination overhead, so avoid locking more data or for longer than necessary. However, correctness comes first: removing a lock without replacing its protection can introduce a race. For frequently read data, consider designs such as immutable snapshots or carefully implemented reader-writer synchronization. These alternatives still require a correct way to publish data and manage object lifetimes.

Conclusion

Thread-safe memory copying in C and C++ is about protecting the bytes and their lifetime—not choosing a special version of memcpy. Use memcpy for nonoverlapping regions, memmove for overlapping ones, and a consistent synchronization or ownership strategy whenever another thread can access the same memory. Validate sizes and pointers, keep locks around the full shared-data access, and design the destination’s ownership just as carefully as the source’s. These habits make concurrent code safer, clearer, and easier to maintain.

Exit mobile version