logoalt Hacker News

sweetjuly • today at 7:12 AM • 1 reply • view on HN

> This will be used to align the data. For some reason, our computers are much better at dealing with data that is aligned at 8 bytes. This means that the start of each new allocation has to be at a multiple of 8 bytes.

Casting a pointer which is not aligned to its natural alignment has undefined behavior in C. It's not just an issue of unaligned accesses being slow; in practice, your program might also crash or access unexpected data on real platforms with real compiler implementations.


Replies

flohofwoe • today at 8:31 AM

There's really no other way for a general allocation function that doesn't know the target type. I would expand the default alignment from 8 to 16 bytes though, because this is what you typically get from malloc on 64-bit targets, and a bigger 'natural alignment' should be extremely rare (maybe needed for some SIMD types, but those are outside the C standard anyway).

> It's not just an issue of unaligned accesses being slow; in practice, your program might also crash or access unexpected data on real platforms with real compiler implementations.

Unaligned accesses are fast (unless they straddle a cache line or involve SIMD registers) and work perfectly well on current mainstream CPUs (and have been working fine for a long time).

E.g. I'm really not a fan of taking every piece of C code apart because it might not work on an experimental CPU design from the 1960s which the C standard theoretically supports but no current C compiler ;) (exaggerating of course, but there's no way around testing on all expected target compilers and platforms, any target config that's not explicitly tested should be considered unsupported, and that's not even a programming language specific thing).

➕ show 1 reply