← Questions

Implement memcpy with misaligned addresses

0
AmazonCodingLast asked Jan 2026

A coding interview question asked in Amazon's coding round, last asked Jan 2026. It tests c++, memory and low-level.

Write memcpy in C: copy n bytes from src to dst. Copying one byte at a time is correct but slow, so copy a machine word (8 bytes) at a time where you can. The catch is alignment: src and dst may each start anywhere, not on a word boundary, and not at the same offset from one.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • void *my_memcpy(void *dst, const void *src, size_t n) — copies n bytes and returns dst. The two regions do not overlap.

Example

src = 0x1003, dst = 0x2005, n = 30, word size 8
# dst is 3 bytes short of the next boundary (0x2008): copy 3 bytes one at a time,
# then 3 whole words to dst 0x2008..0x201f, then the last 3 bytes one at a time.
# src is now at 0x1006, not word-aligned, so the word loads need the
# shift-and-merge technique (or unaligned loads, where the CPU allows them).

Constraints

  • n can be 0 or very large.
  • The target may fault on unaligned word access, so do not assume it is allowed.

Clarifying questions

  • Which architecture: does it support unaligned loads, and at what cost?
  • Can the regions overlap? (If so, that is memmove.)
  • Is the word size 4 or 8 bytes?

What a strong answer covers

  • Three phases: copy single bytes until dst is aligned, copy whole words, copy the remaining tail bytes.
  • When src and dst have the same misalignment, aligning one aligns both. When they differ, read aligned words from src and build each output word by shifting and OR-ing two neighbouring source words, never reading past the end of the source buffer's last word in a way that could fault.
  • Endianness affects the shift directions.
  • Overlap: undefined behaviour for memcpy; for memmove, copy backwards when dst > src and the regions overlap.
  • Tests: n = 0, n smaller than a word, every combination of source and destination offset 0–7, and comparison with byte-by-byte copy.

Follow-ups

  • Implement memmove.
  • Use 16- or 32-byte vector registers. What changes?
  • Strict aliasing: how do you read bytes through a uint64_t * legally in C?

Where it's asked

  • Amazon · Coding · Last asked Jan 202655 min · Usually two rounds; one is often an object-oriented design built in steps · No AI

What it tests

c++ · memory · low-level

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding