Hi, consider this simple program:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <type_traits>
using namespace std;
enum { sz = 8 };
int main() {
cout << alignment_of<int>::value << endl;
char a[sz];
cout << (void*)a << endl;
bzero(a, sz);
*((int*)(a+1)) = -1;
for (int i = 0; i < sz; ++i) printf("%02hhx ", a[i]);
cout << endl;
return 0;
}
Here's the stdout on x86_64:
4
0x7fff0710a2b0
00 ff ff ff ff 00 00 00
I expected a cast-align warning or something. How did gcc make the
unaligned write work? It didn't generate any inefficient code or
anything; here's an excert from objdump -DE:
*((int*)(a+1)) = -1;
400a4a: 48 8d 45 f0 lea -0x10(%rbp),%rax
400a4e: 48 83 c0 01 add $0x1,%rax
400a52: c7 00 ff ff ff ff movl $0xffffffff,(%rax)
Is the alignment_of value incorrect? I also tried __alignof__ and got
the same result.
Related: Is there an example of a type that actually has non-1 alignment
on x86(_64)? What happens if I try to use it as shown above (unaligned)
- does the compiler just produce inefficient code? Does the memory
access fall into alignment (thus producing unexpected results)?
Thanks in advance for any answers.
--
Yang Zhang
http://www.mit.edu/~y_z/