This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Fwd: __attribute__((packed)) seems to break pointer arithmetic
- From: Maxim Yegorushkin <maxim dot yegorushkin at gmail dot com>
- To: gcc-help at gcc dot gnu dot org
- Date: Tue, 19 Feb 2013 12:02:51 +0000
- Subject: Fwd: __attribute__((packed)) seems to break pointer arithmetic
- References: <CAMg=2zLhnbeS1A_jdyb7R5=wWkXATPYRhqMeAU-6=NLKFp31yw@mail.gmail.com>
Hi gcc-help,
I stumbled upon strange behaviour of pointer arithmetic when
__attribute__((packed)) is used. Please consider the following:
$ cat test.cc
#include <cstdio>
#include <cstdint>
struct __attribute__((packed)) Xyz {
uint32_t seq_no;
uint64_t end_offset;
};
struct Mapping {
void* mem;
size_t len;
template<class T>
T* begin() {
return static_cast<T*>(mem);
}
template<class T>
T* end() {
auto e = reinterpret_cast<uintptr_t>(static_cast<char*>(mem) + len);
return reinterpret_cast<T*>(e - e % sizeof(T));
}
};
int main() {
Mapping m{reinterpret_cast<void*>(0x40000u), 0x1000u};
Xyz* beg = m.begin<Xyz>();
Xyz* end = m.end<Xyz>();
size_t len = end - beg;
printf("%p\n", beg);
printf("%p\n", end);
printf("%zx\n", len);
}
$ g++ -o test -std=gnu++11 -Wall -Wextra test.cc
$ ./test
0x40000
0x40ff8
55555555555556aa <---- wrong
When __attribute__((packed)) is removed it correctly outputs:
$ ./test
0x40000
0x41000
100
I checked the documentation for __attribute__((packed)) and it says
nothing about it changing the behaviour of pointer arithmetic. Could
anyone shed some light on this strange behaviour please?
-- Maxim