Skip to main content
gamedev.net
🔒 Locked

Memory Alignment

Started by badmoon Apr 12, 2005 at 3:34 AM 2 replies 800+ views
Original Post
badmoon
badmoon
Hi Given the following the struct:

struct X
{
	_int64			d;
	short			a;
	unsigned char		b;
	short			c;
	int			e;
};

Can anyone tell me exactly why sizeof( X ) is not equal to 17, and what it really ends up being on a PC (using VC 6). I've never been quite clear with the exact inner workings of memory alignment, and was hoping someone could clear this up for me. Thanks
nmi
nmi
Every member of your struct has a certain alignment. The aligment of the struct is the greatest alignment of its members. In your case _int64 has an alignment of 8 bytes, so the alignment of your struct is also 8 bytes.

Imagine you write something like:

X x[30];

This means that x[0], x[1], ... all need an 8 byte alignment. What happens is that the compiler pads the structure to increase its size to be a multiple of the alignment. This way x[0], x[1] and so on all are aligned.
badmoon
badmoon
Thanks very much! That clears it up completely
MaulingMonkey
MaulingMonkey
Quote:
Original post by nmi
Every member of your struct has a certain alignment. The aligment of the struct is the greatest alignment of its members. In your case _int64 has an alignment of 8 bytes, so the alignment of your struct is also 8 bytes.


There's also the alignment of the actual members. I don't have _int64 on my debian box, so I replaced it with a long (4 bytes). Here's what it turned out looking like:

0..3 (4) bytes: D
4..5 (2) bytes: A
6..6 (1) byte : B
7..7 (1) byte : padding, so C is on a 2-byte boundry
8..9 (2) bytes: C
10..11 (2) bytes: padding, so E is on a 4-byte boundry
12..16 (4) bytes: E

Assuming D had been 8 bytes, pretty much everything else would be the same, except shifted down by 4, and there probably would've been a 4 byte padding at the end so that D of the next structure ended up on an 8 byte boundry.

All these positions and offsets are subject to your compiling options and alignment paragmas. That said, you can help your compiler out some by rearanging in this pattern:

struct X{    _int64         d;    int            e;    short          a;    short          c;    unsigned char  b;};


That is, sorting from biggest to smallest, in which case everything ends up allready starting on their boundry, meaning no padding except at the end is necessary. In this case, we'll have just as much padding, but it'll all be at the end.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.