Bug 8355 – struct's sizeof has bug

Status
RESOLVED
Resolution
INVALID
Severity
regression
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2012-07-07T06:37:00Z
Last change time
2012-07-07T16:11:40Z
Assigned to
nobody
Creator
soarowl

Comments

Comment #0 by soarowl — 2012-07-07T06:37:32Z
The following code extract from https://github.com/SiegeLord/Tango-D2.git tango\util\compress\Zip.d --------------------------------------------------------------------- import std.stdio; align(1) { struct LocalFileHeaderData { ushort extract_version = ushort.max; ushort general_flags = 0; ushort compression_method = 0; ushort modification_file_time = 0; ushort modification_file_date = 0; uint crc_32 = 0; // offsetof = 10 uint compressed_size = 0; uint uncompressed_size = 0; ushort file_name_length = 0; ushort extra_field_length = 0; } } void main() { writeln(LocalFileHeaderData.sizeof); } --------------------------------------------------------- The output should be 26 instread of 28.
Comment #1 by nilsbossung — 2012-07-07T12:54:29Z
Comment #2 by bugzilla — 2012-07-07T13:21:52Z
If you're using head, you'll need to put the align(1) inside the struct declaration, rather than outside. The layout is now only affected by align attributes that are inside the declaration. Align attributes outside affect how the struct is aligned where the struct instance is placed. I.e. this is an intentional change. The previous behavior was broken in some respects, and was incompatible with doing things like having 256 byte alignment. Furthermore, the specific behavior of putting align outside and having it affect the inside was a bug.
Comment #3 by bearophile_hugs — 2012-07-07T13:58:13Z
(In reply to comment #2) > If you're using head, you'll need to put the align(1) inside the struct > declaration, rather than outside. The layout is now only affected by align > attributes that are inside the declaration. What's the right syntax? This prints three times 28: struct Foo1 { align(1): ushort a,b,c,d,e; uint f, g, h; ushort i, j; } pragma(msg, Foo1.sizeof); struct Foo2 { align(1) { ushort a,b,c,d,e; uint f, g, h; ushort i, j; } } pragma(msg, Foo2.sizeof); struct Foo3 { align(1) ushort a,b,c,d,e; align(1) uint f, g, h; align(1) ushort i, j; } pragma(msg, Foo3.sizeof); void main() {} While this prints 26: align(1) struct Foo4 { align(1): ushort a,b,c,d,e; uint f, g, h; ushort i, j; } pragma(msg, Foo4.sizeof); void main() {}
Comment #4 by bugzilla — 2012-07-07T16:11:40Z
align inside sets the alignment of the fields. align outside sets the alignment of the instance as a single block. So, you'll need both to get an unaligned size. For example, consider an array of S. It should be an even multiple of the size of S. So consider how alignment must play into that, and the behavior becomes inevitable.