1

The following code defines a packed (alignment 1) structure where the dwBug member is not aligned correctly. If such member is assigned to via means of a reference parameter, the assignemnt fails on architectures that do not support unaligned accesses such as ARM.

I am not 100% sure that what I am doing is legal; my understanding is however that unless I am explicitely casting the compiler should keep a track of whether it can copy data as is or it has to resolve the unaligned access. There are no warnings even with -Wall

#include <stdint.h>
#include <stdio.h>

#pragma pack(1)
typedef struct {
    uint16_t w1;
    uint32_t dwBug;
} STest;
#pragma pack()

class CTest
{
public:
    void testIt()
    {
        copyUnaligned(member.dwBug);
        printf("%08x\n", member.dwBug);
    }

private:
    void copyUnaligned(uint32_t &copyIt)
    {
        copyIt = 0x12345678;
    }

    STest member;
};

int main(int, char **)
{
    CTest test;

    test.testIt();
}

The output of this code is 00001234

# cat /proc/cpuinfo
model name      : ARM926EJ-S rev 5 (v5l)
Features        : swp half fastmult edsp java
CPU implementer : 0x41
CPU architecture: 5TEJ
CPU variant     : 0x0
CPU part        : 0x926
CPU revision    : 5

gcc is a 5.3.1 cross-compiler built for a arm-linux-gnueabi target.

Thanks

numo68
  • 11
  • 1
  • With all the code in the same file i guess the compiler could. But if copyUnaligned was in another file i don't see how the compiler would know about the miss-aligned access. – Richard Critten Mar 29 '17 at 07:45
  • 1
    check out http://stackoverflow.com/questions/8568432/is-gccs-attribute-packed-pragma-pack-unsafe . In short : what you're doing is not guaranteed to work by the compiler - you should get safe code when modifying the field by directly doing `member.dwBug = 0x12345678;` though (ie. don't use a reference to access the field). – Sander De Dycker Mar 29 '17 at 08:01
  • 1
    Your code is invalid. The compiler should complain... – Marc Glisse Mar 29 '17 at 08:04
  • 1
    ok, what @RichardCritten says is a plausible explanation - the callee indeed can't know. The caller knows and should complain. Some more googling brought a [gcc bugzilla thread](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51628#c15) - so it looks like that the developers are aware but did not implement a warning for a whatever reason. Thanks to all that answered. – numo68 Mar 29 '17 at 09:48

0 Answers0