PDA

View Full Version : Question about byte alignment...



chronozphere
24-12-2010, 03:29 PM
Hey all,

Consider the following record:



TMyRecord = record
ID: Word; //2 bytes
recSize: Integer; //4 bytes
Str: String; //4 bytes
b: Boolean; //1 bytes
a: char; //2 bytes
end;


In delphi 2010, when I enable {$A8}, sizeOf(TMyRecord) will return 16. Which strikes me because I thought each field would take 8bytes (or will be padded, until it takes 8 bytes).

It would correspond to the following memory layout:


WWxxxxxx
IIIIxxxx
SSSSxxxx
Bxxxxxxx
CCxxxxxx


However, this is not the case. How exactly are the fields packed together when I use 8-byte alignment? :)

Thanks

virtual
24-12-2010, 07:53 PM
why not using packed record instead

chronozphere
24-12-2010, 07:57 PM
why not using packed record instead?


I know about packed records, but it's not an answer to my question. ;) I just want to know how exactly byte alignment works.

VilleK
24-12-2010, 09:53 PM
I thought this was strange too, but I found this information here: http://www.delphibasics.co.uk/RTL.asp?Name=$Align&ExpandCode1=Yes


With $Align On (default), complex data types, such as records have their elements aligned to 2, 4 or 8 byte boundaries, as appropriate to the data type. For example, a Word field would be aligned to a 4 byte boundary.

Which means that A4 and A8 will only differ if the record contains 8 byte members such as Double or Int64.