So I have the following minimized C11 code that defines a struct containing a uint16_t (which means the struct it should be aligned to 2 bytes) and I want to cast a char buffer to a pointer to that struct.
With warnings turned all up, clang rightly complained that the alignment requirements of the struct are not met. So I added a C11 alignas
specifier to the buffer to make sure the buffer is sufficiently aligned, but that didn't shut up clang.
My question is: am I doing something wrong with alignas
? Or is it just that the -Wcast-align diagnostic is only looking at the type of the arguments and not also at the manually specified alignment? (I realize I can just cast to void*
to silence the diagnostic, but since this piece of code is supposed to be portable, I don't want to side-step the diagnostic unless I am certain it is a false positive.)
#include <stdint.h>
#include <stdalign.h>
struct foo {
uint16_t field1;
};
int main(void) {
alignas(struct foo) char buffer[122] = {0};
struct foo *foo = (struct foo*)buffer;
return foo->field1;
}
Compiler options and error message:
$ clang -ggdb -O3 foo.c -Weverything -Werror -Wno-c++98-compat -Wno-c11-extensions
foo.c:11:23: error: cast from 'char *' to 'struct foo *' increases required alignment from 1 to 2 [-Werror,-Wcast-align]
struct foo *foo = (struct foo*)buffer;
^~~~~~~~~~~~~~~~~~~~~~~~~
Compiler version:
$ clang -v
clang version 3.5.1 (tags/RELEASE_351/final)
Target: x86_64-pc-linux-gnu
Thread model: posix
Selected GCC installation: /usr/lib/gcc/x86_64-pc-linux-gnu/4.8.4
Update: There is no warning when I move the buffer and its alignment into a struct. I interpret this as a hint that clang does indeed only look at the types for this warning.
#include <stdint.h>
#include <stdalign.h>
struct foo {
uint16_t field1;
};
struct bar {
alignas(struct foo) char buffer[122];
};
int main(void) {
struct bar bar = {{0}};
struct foo *foo = (struct foo*)&bar;
return foo->field1;
}
reinterpret_cast
was what I was thinking. I did not look through the source of clang to see how that is handled. – Thor