Remix.run Logo
IshKebab 3 hours ago

There are still modern CPUs that don't support misaligned access. It would be insane for C to mandate that misaligned accesses are supported.

However I do agree that just saying "the behaviour is undefined" is an unhelpful cop-out. They could easily say something like "non-atomic misaligned accesses either succeed or trap" or something like that.

> In the end it's the CPU and not the compiler which decides whether an unaligned access is a problem or not.

Not just the CPU - memory decides as well. MMIO devices often don't support misaligned accesses.

1718627440 an hour ago | parent | next [-]

> They could easily say something like "non-atomic misaligned accesses either succeed or trap" or something like that.

That means that the compiler must emit the read, even if the value is already known or never used, as it might trap. There is a reason for the UB!

thayne 3 hours ago | parent | prev | next [-]

On hardware that doesn't support it, misaligned loads could be compiled to multiple loads and shifts. Probably not great for performance, and it doesn't work if you need it to be atomic, but it isn't impossible.

gizmo686 2 hours ago | parent [-]

That still requires detecting when a misaligned load happens.

account42 2 hours ago | parent | prev [-]

For x86 SSE there are aligned instructions that will trap on unaligned access.