ProgrammingSystem Programmer

How does the standard memcpy function work in C, what is it used for, and what pitfalls may arise when using it to copy memory of different types?

Pass interviews with Hintsage AI assistant

Answer.

The memcpy function from the standard library (string.h) is designed for byte-by-byte copying of memory areas from one location to another. It is a universal tool for copying arrays, structures, and other data blocks where performance is important and type conversion is not needed.

Background: memcpy appeared with the first implementation of the standard library when there was a need to handle "raw" memory blocks, for example, for working with files, network packets, and data serialization. Similar functions are present in almost all low-level languages.

Issue: memcpy only operates on bytes; it does not care about data types, alignment, or overlapping memory areas. Errors in size specification or incorrect areas lead to memory corruption or unexpected results. Moreover, using memcpy for overlapping areas causes undefined behavior.

Solution: Use memcpy only if you are sure:

  • there is no overlap of areas;
  • the copied data is correctly interpreted by the target type;
  • the size of the copied blocks is specified correctly. For overlapping areas, use the memmove function.

Code example:

#include <string.h> typedef struct { int id; float value; } Item; Item src = {42, 3.14f}; Item dest; memcpy(&dest, &src, sizeof(Item)); // copying structure byte by byte

Key features:

  • Does not perform type conversion
  • Does not check for array bounds
  • Can cause UB when the source and target blocks overlap

Trick questions.

Can memcpy be used to copy strings (char)?*

Yes, but only if the length is known exactly. If the string is null-terminated, strcpy or strncpy are often used. If the size is mixed up, it may lead to out-of-bounds memory access or loss of the terminating null.

char src[] = "abc"; char dest[4]; memcpy(dest, src, 4); // 3 letters + '\0' are copied

What happens when copying structures with non-standard alignment or pointers through memcpy?

memcpy does not consider semantics or internal pointers. If a structure holds dynamic fields (e.g., char *buf;), only the address itself is copied, not the contents at that address. This leads to what is known as "shallow" copying.

typedef struct { char *buf; } Wrapper; Wrapper src = {malloc(10)}; Wrapper dest; memcpy(&dest, &src, sizeof(Wrapper)); // Only pointer field, not the content

What will happen if src and dest overlap in memcpy?

The behavior is undefined by the standard, and data loss may occur. For copying with overlap, use memmove:

memmove(dest, src, size); // ensures correct copying

Common mistakes and anti-patterns

  • Copying with overlap between src and dest
  • Errors in counting the number of bytes (not sizeof type, but sizeof pointer)
  • Copying structures with dynamic or hidden resources ("shallow copy" instead of deep)

Real-life example

Negative case

Arrays overlap: memcpy is applied to shift part of the array to the right, src and dest partially coincide.

Pros:

  • Works quickly on most platforms

Cons:

  • Loss of part of the data, UB, unpredictable bugs

Positive case

Using memmove to handle overlapping areas, the volume of data is precisely computed as the number of bytes in the source structure.

Pros:

  • Safe copying
  • Readability and ease of maintenance

Cons:

  • Slightly lower performance compared to memcpy