One of the tests we run is a compile with -Wcast-align
. Its especially helpful when an incorrect cast occurs among floats, doubles and integrals (it will sometimes lead to a SIGBUS
, IIRC).
We have code that essentially performs the following. The actual cases are a little more involved, but this is the essence of the usage:
typedef uint64_t word64;
static const size_t SIZE = ...;
word64 buffer[SIZE] = ...;
And:
DoSomethingWithBuffer(const byte* buff, size_t size)
{
word64* ptr = (word64*)buff;
...
}
The buffer is aligned on an 8 or 16 byte boundary. I've verified the alignment using both manual code reviews and runtime asserts.
The problem is both GCC and Clang warn that the data is unaligned. And it does so nearly 2000 times, so I'm potentially losing real findings. For example:
warning: cast from 'const byte *' (aka 'const unsigned char *') to 'word64 *'
(aka 'unsigned long long *') increases required alignment from 1 to 8 [-Wcast-align]
word64 tmp = *(word64 *)inBlock ^ roundKeys[0];
^~~~~~~~~~~~~~~~~
With Clang, I can instrument with an assert
and the compiler will sometimes take it as a diagnostic hint. But it does not appear to apply in this case. That is, Clang does not make the connection that assert(inBlock % 8 == 0);
means its aligned.
How can I convey to the compiler that the buffer is aligned without suppressing the warning?
As OP existing code base does not need strong type matching, simple defeat most type matching with void*
which will quiet the warnings. Ref also @Ctx
void DoSomethingWithBuffer(const byte* buff, size_t size) {
const word64* ptr = (void*) buff;
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With