AI Interviews · Question

C memory fundamentals: explain memcpy versus memmove, and write an alignment macro.

Coding (DSA) question reported at NVIDIA (2026). Sources, confidence and an answer card.

Researched · updated

infra-098 AI Infra Engineer Classic DSA & object-oriented design Coding (DSA) Medium confidence
On this page

What they’re really asking

If you only remember one thing, say this in the first minute: “memcpy may assume the two ranges don’t overlap; memmove must work even when they do. So memmove copies forwards when the destination starts before the source, and backwards when it starts after, so it never reads a byte it has already overwritten. The alignment macro adds alignment minus one and clears the low bits. It only works when the alignment is a power of two, and it wraps to zero near the largest size, so callers must check.”

The rest of this page explains each part of that answer.

What makes this different from the code you usually write

As a backend engineer you rarely copy raw bytes yourself. The language does it for you: a slice copy, a string builder, a buffer from a library. This question takes the library away and checks whether you know what the library promises.

Two things make it more than a warm-up. First, the promise is subtle: the two functions look identical and differ only when the ranges overlap, and the interviewer wants the one-sentence definition before any code. Second, low-level code has preconditions, conditions the caller must meet for the code to be correct. The alignment macro is correct only for some inputs. A strong answer says which ones, out loud, before being asked.

So the interviewer is testing two things: do you know C memory rules precisely enough to implement them, and do you state what your code assumes?

The question was reported in a first-hand NVIDIA account, which lists “Implement memcpy and memmove from scratch, first defining the difference between them”, and, in the phone interview, “a macro which takes size, alignment as input and returns the next size which is aligned to alignment” (Acedfirst-hand · 2026).

Words you need first

  • Overlap means the source range and the destination range share some bytes, for example when you shift part of a buffer two places to the right.
  • Undefined behaviour is what the C standard calls a case where the program may do anything at all: give the right answer, give a wrong one, or crash. Code that relies on it may work today and break with the next compiler.
  • Alignment is a number, usually a power of two such as 8, 16 or 64, that an address or size should be a multiple of. Hardware reads aligned memory faster, and some instructions require it. “Round 9 up to an alignment of 16” means “give me the smallest multiple of 16 that is at least 9”, which is 16.

Clarify first

Ask these in the first minute. Each one removes a trap.

  • C or C++? Assume C-compatible code, compiled as C++ so you can use static_assert (a check the compiler runs at build time) to prove the macro on known inputs.
  • May your memmove call the library’s memmove? Assume no. Otherwise there is nothing to write.
  • Is the alignment always a power of two? Assume yes, and offer a general version that works for any alignment.
  • Is word-at-a-time copying expected? Assume byte-by-byte first, and mention how real libraries go faster.

Say it like this: “I’ll write the byte-by-byte versions first and state the preconditions in comments. Then I’ll talk about how a real library makes them fast.”

Answer

The definition, in one sentence

memcpy assumes the ranges do not overlap; if they do, “the behavior is undefined” (cppreference). memmove behaves “as if the characters were copied to a temporary character array” (cppreference), so overlap is safe. Libraries get that result without a temporary array: they copy forwards when the destination starts before the source, and backwards otherwise.

A worked example: why the direction matters

Take an 8-byte buffer holding ABCDEFGH. Move 5 bytes from position 0 to position 2. The right result is ABABCDEH: the first five letters, shifted right by two places.

Copy orderWhat happens, step by stepResult
ForwardsCopy position 0 to 2: A lands where C was. Copy 1 to 3: B lands on D. Copy 2 to 4: position 2 now holds A, not C, so A is copied again. The damage repeats.ABABABAH (wrong)
BackwardsCopy 4 to 6 first (E), then 3 to 5 (D), 2 to 4 (C), 1 to 3 (B), 0 to 2 (A). Every byte is read before anything overwrites it.ABABCDEH (right)

The rule falls out of the example. When the destination is after the source, the end of the source is about to be overwritten, so copy from the end. When the destination is before the source, copy from the start.

Say it like this: “If the destination is after the source and they overlap, a forward copy reads bytes it has already overwritten. So I pick the direction by comparing the addresses.”

The code

#define ALIGN_UP(n, a)     (((n) + ((a) - 1)) & ~((a) - 1))   /* a: power of two */
#define IS_POW2(a)         ((a) != 0 && (((a) & ((a) - 1)) == 0))
#define ALIGN_UP_ANY(n, a) ((((n) + (a) - 1) / (a)) * (a))   /* any a > 0 */

void *my_memcpy(void *dst, const void *src, size_t n) {
    unsigned char *d = dst;
    const unsigned char *s = src;
    for (size_t i = 0; i < n; i++) d[i] = s[i];
    return dst;
}

void *my_memmove(void *dst, const void *src, size_t n) {
    unsigned char *d = dst;
    const unsigned char *s = src;
    if (d == s || n == 0) return dst;
    if ((uintptr_t)d < (uintptr_t)s) {             /* integer compare: < on unrelated pointers is unspecified */
        for (size_t i = 0; i < n; i++) d[i] = s[i];          /* forwards */
    } else {
        for (size_t i = n; i > 0; i--) d[i - 1] = s[i - 1];  /* backwards */
    }
    return dst;
}

Why the comparison goes through uintptr_t. uintptr_t is an unsigned integer type wide enough to hold an address. The C standard does not say what “less than” means for two pointers into different objects, and memmove can be called with exactly that. Comparing the addresses as plain integers sidesteps the problem.

Why the backwards loop counts from n down to 1. size_t is unsigned, so a loop that runs i down to 0 and then subtracts 1 would wrap around to a huge number and never stop. Indexing with i - 1 keeps i at 1 or more.

Why the macro works

When the alignment a is a power of two, a − 1 is a block of 1-bits at the bottom of the number. For 16, that is 15, binary 1111. Adding it pushes any size that is not already a multiple past the next multiple. Then & ~(a − 1) clears those bottom bits, which rounds down to that multiple. So ALIGN_UP(9, 16) is 16 and ALIGN_UP(16, 16) is 16: an aligned size stays the same. The bit-by-bit working is in the box below.

IS_POW2 checks the precondition: a power of two has exactly one 1-bit, so a & (a − 1) is zero only for powers of two. ALIGN_UP_ANY works for any positive alignment, at the cost of a divide.

What to say next, without being asked

  • Double evaluation. A macro pastes its arguments in as text, and ALIGN_UP uses a more than once. So ALIGN_UP(x, a++) increments a twice. A static inline function avoids this.
  • Overflow. Near the largest size_t value (SIZE_MAX) the addition wraps around: ALIGN_UP(SIZE_MAX − 3, 8) is 0. A caller that allocates 0 bytes and then writes a large amount has a buffer overflow. Check before allocating.
  • Speed. A production memcpy first aligns the pointers, then copies machine words or vector registers, then the leftover bytes at the tail. That is also why memcpy is allowed to be faster than memmove: with no overlap to worry about, it may copy in any order and any width.
The arithmetic behind the numbers (for a Staff-level follow-up)
  • ALIGN_UP(9, 16): 9 + 15 = 24 = binary 11000. Clearing the low four bits leaves 10000 = 16.
  • ALIGN_UP(16, 16): 16 + 15 = 31 = binary 11111. Clearing the low four bits leaves 10000 = 16.
  • ALIGN_UP(SIZE_MAX − 3, 8): (SIZE_MAX − 3) + 7 = SIZE_MAX + 4, which wraps to 3. Then 3 & ~7 = 0.
  • IS_POW2(12): 12 = 1100, 11 = 1011, and 1100 & 1011 = 1000 = 8, not 0, so 12 is rejected.
  • ALIGN_UP_ANY(9, 12): (9 + 11) ÷ 12 = 1 in integer division, and 1 × 12 = 12.

How it was checked

In the family walkthrough, this code was checked on 2026-10-12 with 20,000 random copies inside a 64-byte buffer, most of them overlapping, compared byte for byte against the library memmove. It ran under AddressSanitizer and UndefinedBehaviorSanitizer, compiler modes that add run-time checks for bad memory access and undefined behaviour. static_asserts cover the macros. Mention a test like this in the interview: a randomized comparison against a trusted reference is the fastest way to catch a direction bug.

Senior vs Staff

The Senior answer is correct code. The Staff answer also says where it stops being correct and why the library is faster.

C memory basics

Senior

  • Correct definition, direction rule, working macro, and a randomized overlap test.

Staff

  • States preconditions and overflow, avoids pointer-comparison undefined behaviour, explains word-sized copying and why memcpy is allowed to be faster.

Small-team version

You will call the library versions. They are faster and tested on every platform, and writing your own costs review time for no gain.

The transferable habit is stating preconditions (power-of-two alignment, no overlap) where callers will see them, and writing a randomized test against a reference whenever you write low-level code, including code an agent wrote. That test is a short loop, and it catches the bugs that reading the code misses.

This question has low relevance to a small team’s AI work unless you write C or CUDA extensions (GPU code you compile yourself). Buy (use the library); build only the test.

Pitfalls

  • Copying forwards in all cases. It corrupts the data whenever the destination overlaps the end of the source.
  • Comparing unrelated pointers with <. The standard leaves the result unspecified; compare as uintptr_t.
  • Using the power-of-two macro for any alignment. For 12 it silently returns wrong sizes.
  • Ignoring overflow and double evaluation. Both are bugs a reviewer will spot, and the interviewer expects you to spot them first.

Go deeper

Family

Systems-level concurrency primitives and race hunting

Four short systems questions: memmove and an alignment macro, a bounded queue many threads share, a thread-safe reference-counted pointer, and a race that only shows up under load. C++ and Go code, run under sanitizers.

Other questions in this family