I'm currently defining a struct in C (in Ubuntu x64). It looks like this:
#include <semaphore.h>
#include <stdio.h>
#include <stdbool.h>
typedef struct key{
sem_t sem;
char name[32];
int val1;
int val2;
char k;
int n;
} Key;
From what I know (correct me if wrong, please), struct members in x64 will align to 8 bytes and in x32 will align with 4 bytes. That's also the reason I chose 32 as the id array size.
What I wanted to know is: as it is (first member being a sem_t (32 bytes apparently), and next members being that or any other thing) will there be any padding between the first (sem) and the second member (name, in this case)? Or are they contiguous? If so, does this hold true for both x32 and x64 (as 32 bytes is a multiple of both 4 and 8 bytes)?
It depends — on the implementation. One question you need to be sure you know the answer to: Why are you worried?
The size of a sem_t
may vary between 32-bit and 64-bit implementations. In general, when N is a power of two, an N-byte object (or an array of N-byte objects) will be aligned on an N-byte boundary. The alignment for double
doesn't always follow this rule. If you had any short
(or uint16_t
) data members, they would only need to be aligned on a 2-byte boundary*. A structure or union type will be aligned according to the alignment requirements of the member with the most stringent alignment requirements.
There won't be any padding bytes between sem
and name
because character strings can be aligned on any boundary. There might be padding bytes between name
and val1
, but you've probably avoided that (in part because you chose the length 32 for name
).
You will have padding between k
and n
; if you reverse their order, you'll (probably) only have trailing padding, but you will have trailing padding because of the single character. As written, you have interior padding (probably 3 bytes of it) and maybe no trailing padding.
To investigate further, you'd need to use the offsetof
macro from <stddef.h>
, but be aware that it can only report on the current implementation, not other implementations.
* Technically, a short
need not be 16 bits or 2 bytes, but it almost invariably is, and I'm assuming as much here.