← Back to context

Comment by matheusmoreira

8 hours ago

Sure you can. In many architectures it works just fine. Works perfectly in x86_64, for example. It's just a little slower.

In many architectures does not mean you can. The standard is supposed to cover all architectures.

  • If some architecture traps on unaligned access, then the compiler can and should simply generate the correct code so that it loads the integer piece by piece instead. Load multiple integers and shift and mask away the irrelevant bits, done. This is exactly what modern architectures already do in hardware. Works, it's just a little slower.

    This is exactly what the compilers do if you use a packed structure to access unaligned data. Works everywhere, as expected. Compilers have always known what to do, they just weren't doing it. C standard says no.

    The fact is the standard is garbage and the first thing every C programmer should learn is that they can and should ignore it. There is never any reason to wonder what the standard is supposed to do. The only thing that matters is what compilers actually do.

    • The pointer might be something you forced. The compiler needs to do the right thing but if you set the pointer to an unaligned address because you have information on the hardware you can get this undefined situation with nothing the compiler can do about it.

      7 replies →

    • But if it's a pointer, the compiler doesn't know the alignment at compile time. Should the compiler insert an alignment check of every pointer access?

      1 reply →

  • That's why we write C instead of assembly, isn't it?

    You could also mandate that a compiler for architectures without unaligned access either has to prove that the access is going to be aligned or insert a wrapper to turn the unaligned access into two aligned ones.

    Just pretending the issue doesn't exist at all and making it the programmer's problem by leaving it as UB in the spec is a choice.