← Questions
Implement memcpy with misaligned addresses
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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)— copiesnbytes and returnsdst. 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
-
ncan 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
dstis aligned, copy whole words, copy the remaining tail bytes. - When
srcanddsthave the same misalignment, aligning one aligns both. When they differ, read aligned words fromsrcand 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; formemmove, copy backwards whendst > srcand the regions overlap. - Tests:
n = 0,nsmaller 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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
