473,756 Members | 2,187 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

structure layout question

Greetings,

Why does the C standard require the members of a structure not be
re-ordered (6.2.5.20)? Padding is allowed, and platform dependent, which
means one cannot rely on the exact layout anyway, so what's the point?

Without this restriction the compiler could layout the structure in the
most efficient way possible, for some definition of efficient. It would
be easy enough to turn this reordering off with a compiler specific
pragma as is often done with padding.

--
Kyle A. York
Sr. Subordinate Grunt
Mar 1 '07 #1
28 3640
In article <11************ ***@sj-nntpcache-2.cisco.com>,
kyle york <ky***@cisco.co mwrote:
>Why does the C standard require the members of a structure not be
re-ordered (6.2.5.20)? Padding is allowed, and platform dependent, which
means one cannot rely on the exact layout anyway, so what's the point?
As best I recall, arbitrary padding is not permitted: only
where required to bring the entry into alignment (where alignment
rules are platform dependant.) So if you know the alignment rules
for (say) a "pure" double, then you also know the alignment
rules for a double embedded in a struct.

In any case, take the structure and wrap it around with a union,
the other member of which is an array of unsigned char. This is
a legal way to get at the bytes that make up the structure without
worrying about trap representations , and there are scenarios you
can construct where the alignment rules provide guarantees about
what will be where in the unsigned char array that wouldn't be met
if reordering was possible. For example, take the offset of a
member that was known to be followed by a char. char is the most
general alignment, so you know it followed -immediately- after the
end of the member. You know the size of the member via sizeof.
So the unsigned char array indexed at the offset of the member,
plus the sizeof the member, is certain to get you to the beginning of
that char -- but if you'd reordered the elements, the char could
be anywhere relative to the member in question.

>Without this restriction the compiler could layout the structure in the
most efficient way possible, for some definition of efficient. It would
be easy enough to turn this reordering off with a compiler specific
pragma as is often done with padding.
And it would be easy enough for a compiler to provide a pragma to
pack efficiently, possibly breaking ordering or possibly requiring
slow movements in and out of internal char buffers if the architecture
doesn't support "move unaligned". You could call it something wild such
as ... ummm, say, #pragma pack
--
There are some ideas so wrong that only a very intelligent person
could believe in them. -- George Orwell
Mar 1 '07 #2
kyle york wrote On 03/01/07 13:06,:
Greetings,

Why does the C standard require the members of a structure not be
re-ordered (6.2.5.20)? Padding is allowed, and platform dependent, which
means one cannot rely on the exact layout anyway, so what's the point?

Without this restriction the compiler could layout the structure in the
most efficient way possible, for some definition of efficient. It would
be easy enough to turn this reordering off with a compiler specific
pragma as is often done with padding.
The first element of a struct must come first, and
must be preceded by no padding. This allows a struct
pointer to be converted to a pointer to the struct's
first element and vice versa, which is a useful property.

Under certain conditions, different struct types
that share a "common initial subsequence" of elements
can be accessed through a pointer to either type, so
long as the accesses are to the common elements. That's
another useful property.

A struct is often not just a bag of related elements,
but also a description of a "published" format. For
example, an image file that starts with a "magic number"
followed by version numbers followed by ... may well be
described by a struct. There are portability issues
with such usages, but they are useful nonetheless.

--
Er*********@sun .com
Mar 1 '07 #3
ro******@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes:

[in a struct]
As best I recall, arbitrary padding is not permitted: only
where required to bring the entry into alignment (where alignment
rules are platform dependant.) So if you know the alignment rules
for (say) a "pure" double, then you also know the alignment
rules for a double embedded in a struct.
This is a nice theory, but I can't see how to back it up with a
quote from the standard. The text of the standard says "There
may be unnamed padding within a structure object, but not at its
beginning." and I don't see any restrictions on that.
--
"I ran it on my DeathStation 9000 and demons flew out of my nose." --Kaz
Mar 1 '07 #4
In article <87************ @blp.benpfaff.o rg>,
Ben Pfaff <bl*@cs.stanfor d.eduwrote:
>ro******@ibd.n rc-cnrc.gc.ca (Walter Roberson) writes:
>[in a struct]
>As best I recall, arbitrary padding is not permitted: only
where required to bring the entry into alignment (where alignment
rules are platform dependant.) So if you know the alignment rules
for (say) a "pure" double, then you also know the alignment
rules for a double embedded in a struct.
>This is a nice theory, but I can't see how to back it up with a
quote from the standard. The text of the standard says "There
may be unnamed padding within a structure object, but not at its
beginning." and I don't see any restrictions on that.
There is a bit more wording that that in C89 3.5.2.1:

Each non-bit-field member of a structure or union object is
aligned in an implementation- defined manner appropriate to its type.

Within a structure object, the non-bit-field members and the units
in which bit-fields reside have addresses that increase in the order
in which they are declared. A pointer to a structure object,
suitably converted, points to its initial member (or if that
member is a bit-field, then to the unit in which it resides), and
vice versa. There may theefore be unnamed padding within a
structure object, but not at its beginning, as necessary to achieve the
appropriate alignment.
Notice that the alignment within the structure is in a manner
"appropriat e to its type". I interpret that as the alignment
appropriate to the type "ex-vivo", outside of structure. I do not
see anything there that would suggest that a member could have one
alignment within structures and a different alignment outside of
structures.

Notice the padding is not "for arbitrary purposes", but only
"as necessary to achieve the appropriate alignment".

I only apply this hypothesis to the padding -inside- the structure,
and not to any "trailing" padding of the structure. For example,
the classic struct {int i; char c;} might have trailing padding
so that you can form effecient arrays of such elements.
--
There are some ideas so wrong that only a very intelligent person
could believe in them. -- George Orwell
Mar 1 '07 #5
ro******@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes:
In article <87************ @blp.benpfaff.o rg>,
Ben Pfaff <bl*@cs.stanfor d.eduwrote:
>>ro******@ibd. nrc-cnrc.gc.ca (Walter Roberson) writes:
>>[in a struct]
>>As best I recall, arbitrary padding is not permitted: only
where required to bring the entry into alignment (where alignment
rules are platform dependant.) So if you know the alignment rules
for (say) a "pure" double, then you also know the alignment
rules for a double embedded in a struct.
>>This is a nice theory, but I can't see how to back it up with a
quote from the standard. The text of the standard says "There
may be unnamed padding within a structure object, but not at its
beginning." and I don't see any restrictions on that.

There is a bit more wording that that in C89 3.5.2.1:

Each non-bit-field member of a structure or union object is
aligned in an implementation- defined manner appropriate to its type.

Within a structure object, the non-bit-field members and the units
in which bit-fields reside have addresses that increase in the order
in which they are declared. A pointer to a structure object,
suitably converted, points to its initial member (or if that
member is a bit-field, then to the unit in which it resides), and
vice versa. There may theefore be unnamed padding within a
structure object, but not at its beginning, as necessary to achieve the
appropriate alignment.

Notice that the alignment within the structure is in a manner
"appropriat e to its type". I interpret that as the alignment
appropriate to the type "ex-vivo", outside of structure. I do not
see anything there that would suggest that a member could have one
alignment within structures and a different alignment outside of
structures.
Interesting, I hadn't noticed that nuance.

But I don't think that "appropriat e to its type" means that there
couldn't be more padding than necessary, or that it must be the
same padding as outside an structure.
Notice the padding is not "for arbitrary purposes", but only
"as necessary to achieve the appropriate alignment".
The sentence "There may therefore..." was changed in C99 to
"There may be unnamed padding within a structure object, but not
at its beginning." (as I quoted earlier), which may indicate a
change in requirements by the Standard. (But I do not know.)
--
"I ran it on my DeathStation 9000 and demons flew out of my nose." --Kaz
Mar 1 '07 #6
Walter Roberson wrote On 03/01/07 14:17,:
[concerning "excessive" padding in structs]

Notice the padding is not "for arbitrary purposes", but only
"as necessary to achieve the appropriate alignment".
I don't think "appropriat e" implies "minimal." The
Rationale gives some hints as to how the authors wanted
these passages understood:

3.5.2.1 Structure and union specifiers
...
Since some existing implementations , in the interest
of enhanced access time, leave internal holes larger
than absolutely necessary, [...]

(As the section number indicates, this is from the original
ANSI C Rationale and not from a more recent ISO version. The
text might therefore be considered "closer" to the original
authors' thinking on the matter.)

--
Er*********@sun .com
Mar 1 '07 #7
"kyle york" <ky***@cisco.co mwrote in message
news:11******** *******@sj-nntpcache-2.cisco.com...
Why does the C standard require the members of a structure not be
re-ordered (6.2.5.20)? Padding is allowed, and platform dependent,
which means one cannot rely on the exact layout anyway, so what's
the point?

Without this restriction the compiler could layout the structure in the
most efficient way possible, for some definition of efficient. It would be
easy enough to turn this reordering off with a compiler specific pragma as
is often done with padding.
The standard's wording guarantees that two structs defined with the same
initial elements will be laid out the same way in memory and that, as long
as you access only common members, they will be interchangeable . It also
means that any later elements that are not common will be laid out _after_
the common ones, not interspersed with the common ones.

If a compiler was allowed to reorder the elements, these properties would
not hold and a lot of code would break.

S

--
Stephen Sprunk "Those people who think they know everything
CCIE #3723 are a great annoyance to those of us who do."
K5SSS --Isaac Asimov

--
Posted via a free Usenet account from http://www.teranews.com

Mar 1 '07 #8
Stephen Sprunk wrote:
"kyle york" <ky***@cisco.co mwrote in message
news:11******** *******@sj-nntpcache-2.cisco.com...
>>Why does the C standard require the members of a structure not be
re-ordered (6.2.5.20)? Padding is allowed, and platform dependent,
which means one cannot rely on the exact layout anyway, so what's
the point?

Without this restriction the compiler could layout the structure in the
most efficient way possible, for some definition of efficient. It would be
easy enough to turn this reordering off with a compiler specific pragma as
is often done with padding.


The standard's wording guarantees that two structs defined with the same
initial elements will be laid out the same way in memory and that, as long
as you access only common members, they will be interchangeable . It also
means that any later elements that are not common will be laid out _after_
the common ones, not interspersed with the common ones.

If a compiler was allowed to reorder the elements, these properties would
not hold and a lot of code would break.
Just to add to this, the above guarantee is important where structures
are members of a union and the first member or members are used to
identify the appropriate type. One example of this is the X-windows
event object which is a union of all possible event structs.

--
Ian Collins.
Mar 1 '07 #9
In article <45************ **********@free .teranews.com>,
Stephen Sprunk <st*****@sprunk .orgwrote:
>The standard's wording guarantees that two structs defined with the same
initial elements will be laid out the same way in memory and that, as long
as you access only common members, they will be interchangeable .
C89 makes that guarantee where the two structs are the common
prefix of a union encompassing both, but does C89 or C99 promise
it if not union is involved?
--
All is vanity. -- Ecclesiastes
Mar 1 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
5338
by: FISH | last post by:
Ever have one of those days when you're not sure if it's you who's gone mad, or the rest of the world? I have an Open Source project on SourceForge for communication with YSMG - Yahoo's IM protocol. I keep the project source in three directories, based upon the code's function: one for the network API code itself, one for the support APIs (basic chat spam filtering, Swing models, rich text decoders, etc), and one for the test client...
3
3513
by: zhphust | last post by:
I want to convert a object of a managed class to a unmanaged structure that has the same member with that managed class. Can anybody tell me how i can do it? Thanks in advance. -- zhphust ------------------------------------------------------------------------
9
2090
by: neoswf | last post by:
hey guys ive looked at http://news.google.com page code layout, and ive seen that the page layout is table based. the containers are tables, the hidden personalization panels are also in tables. most of the page in build using tables. even the pictures are in cellspacing=5 tables.
20
2319
by: Lalatendu Das | last post by:
hi let's say i have a structure struct test { int A; char B; int C; }; this above structure defination always going to take 16 byte in memeory in whatever manner we align the member variables while declaring a variable to it . because variable 'A' going to take 4 byte then four charachter of
10
4994
by: David Fort | last post by:
Hi, I'm upgrading a VB6 app to VB.net and I'm having a problem with a call to a function provided in a DLL. The function takes the address of a structure which it will fill in with values. I get an error: ---------------- An unhandled exception of type 'System.NullReferenceException' occured in
1
442
by: Falko Wagner | last post by:
Hi there, I am currently translating a VB 6.0 application to .NET and have the following problem: The data structure I need to pass to a DLL function call has a structure variable inside its structure: Private Structure CstData_type Dim Cst_AZ As DbLong
2
2299
by: Francesco | last post by:
Hi there! I'm trying to organize my sources into a webroot tree like this, webroot index.htm - only contains index.php into a frame index.php - require_once('inc/layout.php') home page1.php - require_once('../inc/layout.php') page2.php - require_once('../inc/layout.php')
76
4152
by: jacob navia | last post by:
Since standard C doesn't provide any way for the programmer to direct the compiler as to how to layout structures, most compilers provide some way to do this, albeit in different forms. Microsoft (and lcc-win) uses #pragma pack(1) Gcc uses __attribute__ {(packed)}
9
2521
by: A n g l e r | last post by:
Hi all. I've got the following code as a part of managed C++ library that is loaded by a project in C#: public ref class FlyCaptureEnumsAndStructsManaged { public: typedef enum class FlyCaptureCameraModel { blabla, blabla2 };
0
9152
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9716
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9571
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6410
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4996
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5180
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3676
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3185
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2542
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.