http://gcc.gnu.org/bugzilla/show_bug.cgi?id=56394



             Bug #: 56394

           Summary: pointer arithmetic breaks with __attribute__((packed))

    Classification: Unclassified

           Product: gcc

           Version: 4.7.2

            Status: UNCONFIRMED

          Severity: major

          Priority: P3

         Component: c++

        AssignedTo: unassig...@gcc.gnu.org

        ReportedBy: maxim.yegorush...@gmail.com





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



If -O optimization switch added the output is correct:



    $ g++ -o test -O -std=gnu++11 -Wall -Wextra test.cc

    $ ./test

    0x40000

    0x40ff8

    154 <---- correct





When __attribute__((packed)) is removed it also correctly outputs:



    $ ./test

    0x40000

    0x41000

    100 <---- correct



I looked at the documentation for __attribute__((packed)) and it says nothing

about it changing the behaviour of pointer arithmetic.

Reply via email to