4

I am using ARM. I got alignment fault due to read/write in odd offset(we knew ARM is 4 byte aligned). All the structs defined in my program is single - byte aligned like

#pragma pack(push, 1)    

typedef struct
{
   char a1;
   int  a2;
   char a3;
}a;

#pragma pack(pop)

I am trying to do

#pragma pack(push, 1)

typedef struct
{
    char a1 __attribute__ ((aligned (4)));
    int  a2;
    char a3;
}a;

#pragma pack(pop) 

the gcc attribute _attribute_ ((aligned (4))) makes no effect.

Note :: The above code is not my actual code. sample scenario. 


so I re-arranged structure member to solve the alignment issue. I want to ensure whether the re-arranging is the possible solution or we can make _attribute_ to work on this scenario. Any other solutions are welcome. Thanks in advance.

6
  • Seem that the #pragma overrides the _ attibute . Is is possible to remove the #pragma? And use _ _attribute _ ((packed)) when necessary? Commented Jul 19, 2012 at 10:27
  • I cant remove #pragma.I m reading USB data like that. Those structs should be single-byte packed. Commented Jul 19, 2012 at 10:30
  • Ok, then you can set ((packed)) attribute only for thos USB structs, and remove the pragma. Commented Jul 19, 2012 at 10:32
  • The first member of a struct starts at offset 0, so it must have the same alignment as the struct itself. Commented Jul 19, 2012 at 10:32
  • so I cant use attributes inside #pragma??? Commented Jul 19, 2012 at 10:33

1 Answer 1

1

You can safely read/write char/int in byte-aligned structs on ARM, compiler take care about alignment. Single problem can occur with alignment issue is with the casting to 32 bit int like this:

char buf[5];
char *p = buf + 1;
*((int *)p) = 1;

Note: if you for some reasons like align some member (from begin of the struct) you can use following trick:

typedef struct {
    struct {} __attribute__ ((aligned (4)));
    char a1; // offset is 4
    int  a2; // offset is 5
    char a3; // offset is 9
} a;
Sign up to request clarification or add additional context in comments.

6 Comments

Is it possible to align a struct member to 4-byte if that struct is single-byte aligned using #pragma???
You can: try to do this: int __attribute__((aligned (4))) a2;
Tried. no change in struct size. gives 6 only.
Note: I want to align a1(char), not a2.
I like questions of this type.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.