Alex Rivera | Logout

C(++) struct force extra padding

Asked 2012-06-22T16:41:46.807
10

I've seen countless questions of the form "I don't like padding how do I turn it off", but have yet to find anything about forcing the compiler to provide extra padding.

The specific case that I have looks like

struct particle{
  vect2 s;
  vect2 v;
  int rX;
  int rY;
  double mass;
  int boxNum;
};

Where vect2 is a simple struct {double x; double y;} vect2. In order to use SSE2, I need to be able to load a pair of doubles, aligned to 16 byte boundaries. This used to work, until I added the extra int, pushing my struct size from 48 bytes to 56 bytes. The result is segfaults.

Is there some kind of compiler directive I can use that either says "pad this struct to make it a multiple of 16 bytes long", or "this struct has an alignment of 16-bytes"? I know I could do it manually (tacking on an extra char[12], for example), but I'd really rather just tell the compiler(GCC, preferably ICC compatible), and not have to do it manually if I change the struct in future.

Edit
Report

1 Answer

2

I'm adding my own answer to this, in case someone comes looking for a solution. Mark's solution is a neat one, and fulfills the automatic requirement, but it is not when I ended up going with. I wanted to avoid this, which is why I asked the question, but there is a "trivial" solution:

struct particle{
  vect2 s;
  vect2 v;
  int rX;
  int rY;
  double mass;
  int boxNum;
  char padding[12];
};

By manually checking the current size of the struct, you can add an appropriate number of chars, (or anything else, but char's let you do it in bytes), to make it the right size. This showed the best performance, as well as simplicity, even though it does require updating every time the struct changes. In this case that is fine, although if you had a struct that could change size depending on options, that would be problematic.

Note that my struct was 56 bytes, and I added 12 to make it 64. That math doesn't work, because the trailing int was already being padded out by 4 bytes to the 8-byte boundary; the struct was actually only 52 bytes before. Adding only 5 chars would have worked, by making the struct 57 bytes long, which would have been padded out to 64, but that is not as nice a solution, which is why I used 12 to make it work out exactly.

answered 2012-06-23T18:04:05.573

Your Answer