r/C_Programming • u/xmanotaur • 3h ago
Question Question about alignment in a custom memcpy implementation
I'm implementing my own memcpy as an exercise.
My current approach is:
- Copy bytes until
dstreaches a 4-byte-aligned address. - Copy 4 bytes at a time using
uint32_t. - Copy the remaining bytes one by one.
I understand that this optimization works nicely when src and dst have the same alignment offset, e.g.:
src = 0x1001
dst = 0x2001
src % 4 == dst % 4
What I don't understand is why I can't simply perform an unaligned 32-bit load/store when the offsets are different.
For example:
src = 0x1001
dst = 0x2002
Why can't I simply do:
uint32_t x = *(uint32_t *)src;
*(uint32_t *)dst = x;
This seems like it should copy exactly the desired 4 bytes.
I understand that unaligned accesses may be slower, fault on some architectures, or have restrictions for MMIO. But assuming I'm on an architecture where unaligned 32-bit accesses are supported, is there actually a correctness problem?
I'm trying to understand the fundamental reason rather than just memorize the "same alignment" rule.
Thanks!