Also noticed that with -O3 it produces correctly working code in both cases. Maxim On 19 February 2013 12:02, Maxim Yegorushkin <maxim.yegorushkin@xxxxxxxxx> wrote: > 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