473,765 Members | 2,086 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

struct and union alignment


I would like to check if I understand the following excerpt correctly:

6.2.5#26 (Types):
All pointers to structure types shall have the same representation and
alignment requirements as each other. All pointers to union types shall
have the same representation and alignment requirements as each other.

Does it mean that *all* structure (or union) types have the same
alignment?
Eg. type
struct { char c; }
and
struct { long double ldt[11]; }
have the same alignment requirements?
If the answer to the above is "yes", then it means that:

1. Alignment of any struct (union) must be maximum or its multiple.
(Alignment of a struct (union) can't be less restrictive than that
of its members[*]. Since any (object) type may be a member, at
least one struct (union) must have at least that type's alignment.
Since all struct (union) types have the same alignment,
it follows that all must meet the the maximum one.)

2. Alignment requirements for all structs _and_ unions are the same.
(Since you can have a struct as a member of a union, and a union as a
member of a struct, it follows that their alignments must be the same).
[*] During google search I have learned that a type's alignments
may differ in a struct and outside. Here I rather mean the least
restrictive alignment requirement for a type that has to be met
for a particular architecture.
--
Stan Tobias
sed 's/[A-Z]//g' to email
Nov 14 '05
67 10754
"Mabden" <mabden@sbc_glo bal.net> writes:
"Flash Gordon" <sp**@flash-gordon.me.uk> wrote in message
news:ps******** ****@brenda.fla sh-gordon.me.uk...
On 23 Sep 2004 19:10:38 GMT
"S.Tobias" <sN*******@amu. edu.pl> wrote:
> Does it mean that *all* structure (or union) types have the same
> alignment?
> Eg. type
> struct { char c; }
> and
> struct { long double ldt[11]; }
> have the same alignment requirements?


Unions also have the caveat that they be aligned according to the most
restrictive item in the union. So a struct {char a; double z;} could
have a different alignment than union {char a; double z;}.


Both unions and structs have to be aligned at least as strictly as
their most strictly aligned member. Both struct {char a; double z;}
and union {char a; double z;} have to be aligned in a way that allows
the 'z' member to be accessed. (This can require padding between
members, and possibly after the last member, for a struct; any padding
in a union occurs after each member, since all members have the same
offset.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #11
S.Tobias wrote:
I'm sorry, but I can't see how can you define a pointer to anonymous
struct in the first place (since that struct has no name).


struct {
int a;
int b;
} *pointer_to_ano nymous_struct;
Christian
Nov 14 '05 #12
Keith Thompson <ks***@mib.or g> wrote:
For example, a pointer object might require 4-byte alignment, whereas
a char object requires only 1-byte alignment. When the standard says
void* and char* have to have the same alignment requirements, the
intent is that they're interchangeable as arguments to functions.
Right.
extern char *pc;
void free(void *p);
free(pc); //correct

(Note: we don't need same representation requirement in the above
example. This requirement is necessary eg. for variadic arguments:
printf("%p", pc);
- no cast to void* required.)
Requiring 1-byte alignment for char* but only 4-byte alignment for
void* could break this.
No. I see no reason to require same alignment for types void* and char*,
because in function arguments they're passed by *value* (think conversion).
Similarly, long and char do not have to have same alignment, but we may
always use them in arguments "interchangeabl y":
extern long l;
extern char c;
int f_char(unsigned char c);
int f_long(unsigned long l);
f_char(l); //both calls correct
f_long(c);

Look at the other references to alignment requirements in 6.2.5; they
clearly refer to the alignment of the type itself. 6.2.5#26 uses
similar wording, so it refers to the alignment of the pointers
themselves. (Alignment requirements for character types are discussed
elsewhere.)
I have looked in the entire text. The Standard uses the word "alignment"
in three ways: type (or object) alignment; pointer value alignment
(it uses words: "value", "result", "address"); or pointer alignment
(the way we discuss now).

The last manner is also found in: 6.3.2.3#7 (Pointers) and 7.20.3#1
(Memory management functions). See for yourself: in both cases "pointer
alignment" refers to the pointer *value*, not pointer type.
Barry Schwarz <sc******@deloz .net> wrote: On 23 Sep 2004 23:51:44 GMT, "S.Tobias" <sN*******@amu. edu.pl> wrote:
Strictly speaking, (complete) _types_ have alignment requirements.
As I understand it, when we say "a pointer to TYPE has alignment
requirements ", we mean exactly same thing as: "TYPE has alignment
requirements "; I don't see any reason to differentiate between these two. Actually, this is informally speaking, not strictly speaking.
Informally, some talk about aligning a pointer when we really mean
aligning the *VALUE* assigned to the pointer which is equivalent to
aligning the object the pointer points to. Strictly speaking, when we talk about aligning a pointer we mean
aligning the pointer itself. (I have also considered "pointer to struct" type (ie.: struct s *)
alignment requirements, but this doesn't make sense in context of
the quoted part of the Standard.)


So this is actually what you and Keith think the Standard refers to!
So the fight is over "strictly" and "informally ". I think that
the Standard in all cases means "informally ".

Just as note, this is what allows a struct type to contain a member
which is a pointer to the same struct type (think linked list). At
the time the member is being processed by the compiler, the alignment
requirements of the struct are not yet known (the struct is still
incomplete) but the alignment requirements of the pointer are known so
the compiler can decide how much padding is needed.


While this might be a problem, I agree, this is an internal matter
of the implementation how it solves this (pointer type alignment and
padding before it). The Standard is a contract between an implementor
and a programmer. There is nothing a programmer can gain from
knowing that all pointer-to-struct types have same alignment and
thanks to it the compiler can easily construct a structure type.
I just think your argument misses the point.

OT:
The compiler might construct a struct type in several passes, each
time adjusting the padding before the pointer member.
This process must end, because there exists a maximum alignment.
========

My arguments:
6.2.5#26 (extended quote, to get more context)
A pointer to void shall have the same representation and alignment
requirements as a pointer to a character type.39) Similarly,
pointers to qualified or unqualified versions of compatible types
shall have the same representation and alignment requirements. All
pointers to structure types shall have the same representation and
alignment requirements as each other. All pointers to union types
shall have the same representation and alignment requirements
as each other. Pointers to other types need not have the same
representation or alignment requirements.

39) The same representation and alignment requirements are meant
to imply interchangeabil ity as arguments to functions, return
values from functions, and members of unions.

Rationale:
[...] A pointer to void must have the same representation
and alignment as a pointer to char; the intent of this rule is
to allow existing programs that call library functions such as
memcpy and free to continue to work.

Remark: It is obvious the Standard means "pointers to (structure types)",
not "(pointers to structure) types". This follows from English grammar
rules, but please don't ask me for chapter and verse! :-)

The first part the Std talks about the "compatibil ity" of void* and char*
types. Here it definitely refers to alignment of pointer *values*.
This is required for conversions between void* and char* to be well
defined. Of course, the Std cannot say directly about requirements
for the types they point to, because void is not a complete type (but
this is the intention if we forget it for a while and treat void as an
integer type with size one, but not compatible with char).
(OTOH the Std could formally define alignment of void type to be equal
to that of char type.)

The Standard cannot refer to the alignment of _types_ void* and char*.
If it did, it would only concern conversions between void** and char**.
The only standard functions with that type are strto?() family and friends
(and then we should add same requirement for wchar_t* to be consistent).
The rationale mentions only functions like free() or memcpy(), ie. ones
that probably historically had int free(char*) prototypes before the
type void was introduced. Here, the alignment compatibility between
the _values_ of type void* and char* is essential - IOW it means the
resolution of void* and char* pointer types is the highest and both
are equivalent in this matter.

Then, after the word "Similarly" , the Standard talks about alignment
of pointers to compatible types, struct and unions, and other types in
the same manner. There is no reason to believe it uses similar wording
in a different manner this time.

There is no advantage in guaranteeing same alignment for "pointers
to incompatible types" types (at least I can't think of any).
All of them can be stored as void* if need be.

--
Stan Tobias
sed 's/[A-Z]//g' to email
Nov 14 '05 #13
Christian Kandeler <ch************ ****@hob.de_inv alid> wrote:
S.Tobias wrote:
I'm sorry, but I can't see how can you define a pointer to anonymous
struct in the first place (since that struct has no name).

struct {
int a;
int b;
} *pointer_to_ano nymous_struct;


OIC, didn't think of that.

But then again, what would be a use for that? Since
this is not a struct object definition, there are no objects
of type pointer_to_anon ymous_struct points to.

Mmmm, could it be:
pointer_to_anon ymous_struct = malloc(sizeof *pointer_to_ano nymous_struct);
?
But what is the point in having an anonymous struct then?

Could you supply a real-life example?

--
Stan Tobias
sed 's/[A-Z]//g' to email
Nov 14 '05 #14
"S.Tobias" <sN*******@amu. edu.pl> wrote:
Christian Kandeler <ch************ ****@hob.de_inv alid> wrote:
S.Tobias wrote:

I'm sorry, but I can't see how can you define a pointer to anonymous
struct in the first place (since that struct has no name).

struct {
int a;
int b;
} *pointer_to_ano nymous_struct;


OIC, didn't think of that.

But then again, what would be a use for that? Since
this is not a struct object definition, there are no objects
of type pointer_to_anon ymous_struct points to.

Mmmm, could it be:
pointer_to_anon ymous_struct = malloc(sizeof *pointer_to_ano nymous_struct);
?
But what is the point in having an anonymous struct then?

Could you supply a real-life example?


Maybe something like:

int main() {
uint32 x = 0x5678abcd;
struct {
uint16 hiword;
uint16 loword;
} *wordsinlong = &x;
printf("Hiword: %x\nLoword: %x",
words_in_long->hiword,
words_in_long->loword);
return 0;
}

--
Simon Stienen <http://dangerouscat.ne t> <http://slashlife.de>
»What you do in this world is a matter of no consequence,
The question is, what can you make people believe that you have done.«
-- Sherlock Holmes in "A Study in Scarlet" by Sir Arthur Conan Doyle
Nov 14 '05 #15
In <2r************ *@uni-berlin.de> "S.Tobias" <sN*******@amu. edu.pl> writes:
Keith Thompson <ks***@mib.or g> wrote:
"S.Tobias" <sN*******@amu. edu.pl> writes:
> 6.2.5#26 (Types):
> All pointers to structure types shall have the same representation and
> alignment requirements as each other. All pointers to union types shall
> have the same representation and alignment requirements as each other.
>
> Does it mean that *all* structure (or union) types have the same
> alignment?

No, it's referring to the alignment of the pointer, not the alignment
of the struct or union.


What's the difference?


If you can't grasp the difference between a pointer and the pointed-to
object, stop messing with the C standard and read K&R2 (again).

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #16
"Mabden" <mabden@sbc_glo bal.net> wrote in message
news:mB******** *******@newssvr 14.news.prodigy .com...
"Flash Gordon" <sp**@flash-gordon.me.uk> wrote in message
news:ps******** ****@brenda.fla sh-gordon.me.uk...
On 23 Sep 2004 19:10:38 GMT
"S.Tobias" <sN*******@amu. edu.pl> wrote:
Does it mean that *all* structure (or union) types have the same
alignment?
Eg. type
struct { char c; }
and
struct { long double ldt[11]; }
have the same alignment requirements?


Unions also have the caveat that they be aligned according to the most
restrictive item in the union. So a struct {char a; double z;} could
have a different alignment than union {char a; double z;}.


Wrong. Both the struct and union have the same
alignment as double. A struct's alignment is
the same as the strictest (widest) alignment
of any of its members, including nested aggregates.
Same rules apply for union. The alignment is that
of the strictest alignment of any of its members,
including nested aggregates (other unions or
structs).

Maybe you are confusing the size with alignment?
Nov 14 '05 #17
In <2r************ *@uni-berlin.de> "S.Tobias" <sN*******@amu. edu.pl> writes:
Christian Kandeler <ch************ ****@hob.de_inv alid> wrote:
S.Tobias wrote:
> I'm sorry, but I can't see how can you define a pointer to anonymous
> struct in the first place (since that struct has no name).

struct {
int a;
int b;
} *pointer_to_ano nymous_struct;


OIC, didn't think of that.

But then again, what would be a use for that? Since
this is not a struct object definition, there are no objects
of type pointer_to_anon ymous_struct points to.

Mmmm, could it be:
pointer_to_anon ymous_struct = malloc(sizeof *pointer_to_ano nymous_struct);
?
But what is the point in having an anonymous struct then?


Look at it the other way round: in your own example, what would be the
point of using a tag in the structure definition?
Could you supply a real-life example?


Sure:

struct { ... } foo, bar, baz;

foo, bar and baz are all the objects of this type needed by the program
and they are used in a single translation unit. What would a tag buy you?

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #18
Dan Pop <Da*****@cern.c h> wrote:
In <2r************ *@uni-berlin.de> "S.Tobias" <sN*******@amu. edu.pl> writes:
Keith Thompson <ks***@mib.or g> wrote:
No, it's referring to the alignment of the pointer, not the alignment
of the struct or union.
What's the difference?

If you can't grasp the difference between a pointer and the pointed-to
object, stop messing with the C standard and read K&R2 (again).


Why being so aggressive at me? My seemingly naive question was not
asked without a reason, which I explained at length in my answer
to Barry Schwarz' post (I assume that hadn't reached you before
you sent yours). I think my remark in parentheses (which you didn't
quote) more than suggests I do understand the difference between
pointer type and pointed to type (I explicitly wrote that I did consider
pointer type alignment possibility, but rejected it).

I don't understand how you can judge other people's understanding
only after one posting. Please, explain yourself.

--
Stan Tobias
sed 's/[A-Z]//g' to email
Nov 14 '05 #19
In article <news:2r******* ******@uni-berlin.de>
S.Tobias <sN*******@amu. edu.pl> wrote:
[much snippage]
The last manner is also found in: 6.3.2.3#7 (Pointers) and 7.20.3#1
(Memory management functions). See for yourself: in both cases "pointer
alignment" refers to the pointer *value*, not pointer type.


I am not going to address most of this (due to lack of time), but
I want to make several points here.

First, the value of a pointer to some type "T" -- i.e., a value of
type "T *" -- indeed possesses this "alignment" characteristic, so
that it is possible to ask whether such a pointer is correctly
aligned. (This question is inherently machine-dependent, however,
and on *some* machines it is meaningless.)

But note that if we store this pointer value in an object:

T *pointer_object ;

we then have an *object*, not a variable. This object can have an
address:

T **p2 = &pointer_object ;

(here the object's address is stored in yet another object, "p2",
of type "T **). If "pointer_object " has an address, that value --
a value of type "T **" -- *also* possesses this "alignment"
characteristic. Thus, we can ask not only whether the value stored
in "pointer_object " is correctly aligned, but also whether
"pointer_object " itself is correctly aligned. Having stored
&pointer_obj ect in p2, we can then ask whether "the object p2" is
correctly aligned, via this question:

"does &p2 satisfy its machine-dependent alignment constraints?"

and if we store &p2 in yet another object:

T ***p3 = &p2;

we can then go on to ask whether "the object p3" (or more precisely,
the value produced by &p3) is correctly aligned, and so on.

There are thus four possible machine-dependent alignment constraints
arising so far:

(1) the value stored in pointer_object (of type "T *")
(2) the value produced by &pointer_obj ect (type "T **")
(3) the value produced by &p2 (type "T ***")
(3) the value produced by &p3 (type "T ****")

and it makes some sense to ask whether all of them are satisified,
and to ask whether any or all four of these machine-dependent
alignment constraints are identical. Some of the answers are of
course machine-dependent. Since the objects named "pointer_object ",
"p2", and "p3" are allocated by the compiler, they had better be
correctly aligned -- the C programmer is not the one responsible
for this -- but the rest of the answers require looking at the
machine.

For a number of existing, even common, machines today, the alignment
constraints for "T *" and "T **" often differ, depending on T.
For instance, "char *" always, by definition, needs only 1-byte
alignment ("C byte", not necessarily 8-bit-octet, although the
machines I am thinking of happen to have 8-bit C bytes too); but
"char **" often requires 4 or 8 byte alignment (32-bit or 64-bit
SPARC and MIPS, for instance).

Now, given the original example, or something at least close to
it:

struct C { char c; };
struct D { double d; };

you will find that, e.g., SPARC systems have sizeof(struct C) == 1
and align "struct C" objects on byte boundaries, while sizeof(struct D)
== 8 and "struct D" objects are always found on 8-byte boundaries.
Nonetheless, on those machines in 32-bit mode (or always for V8 and
earlier SPARC systems), "struct C *" and "struct D *" objects
are always aligned on 4-byte boundaries. In other words, given:

struct C *p1, **p2;
... set p1 and p2 ...

we can test the "alignment validity" (on that SPARC machine, in a
machine-dependent manner) with:

int is_p1_aligned(v oid) {
/* p1 is always properly aligned */
return 1;
}

int is_p2_aligned(v oid) {
/* p2 is properly aligned if and only if its low 2 bits are 0 */
return ((int)p2 & 3) == 0;
}

If we add "struct D *p3", however, the "is_p3_alig ned" test becomes:

int is_p3_aligned(v oid) {
/* p3 is properly aligned if and only if its low 3 bits are 0 */
return ((int)p3 & 7) == 0;
}

Thus, the "aligned-ness" of a pointer depends on its type as well as
its value; and for two "struct T1 *" and "struct T2 *" values, the
"aligned-ness" of those two value may require different tests.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #20

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

Similar topics

18
9400
by: Panchal V | last post by:
I want to access a variable length record in C, the format is as follows : +---+---+-----------+ | A | L | D A T A | +---+---+-----------+ A - Some Data (1 BYTE) L - Length the Data that follows (1 BYTE) then actual data
0
1332
by: Urs Vogel | last post by:
Hi when setting the struct member alignment of a mixed code project to 'default', what is the actual alignment? I need to know since we're creating (struct-) data dynamically and pass it to a third party component which expects a 'default' member alignment. Thanks, Urs
4
4663
by: myfavdepo | last post by:
Hi friends, i am having some trouble in my prog. with struct member alignment. I have two different static libraries that i use, each with "struct member alignment" set to 8 bytes. In my application it has to be 2 bytes and when i terminate the my program i am getting this error: DAMAGE: after Normal block (#73) at 0x00323098. When i changed the alignment to 2 bytes for both libraries it run and terminated with out any errors. But one...
2
16135
by: cr55 | last post by:
I was wondering if anyone can help me with this programming code as i keep getting errors and am not sure how to fix them. The error code displayed now is error: C2228: left of '.rent' must have class/struct/union type.The problem area is underlined. Any help will be greatly appreciated. #include <c:\cpp\input.h> #include < time.h> #define SIZE 20 struct Cust{ int custno; char fname;
5
2643
by: xmllmx | last post by:
Please forgive me for cross-posting. I've post this to microsoft.publoc.vc.mfc. But I can't get any response. Maybe only MFC- related topics are cared there. To begin with code: union XXX { double a; char b;
2
14904
by: yalbizu | last post by:
#include <iostream> #include <string> #include <fstream> #include <iomanip> using namespace std; const int NO_OF_STUDENTS=20; struct studentType { string studentFName; string studentLName;
18
6088
by: Bryan Parkoff | last post by:
I hate using struct / union with dot between two words. How can I use one word instead of two words because I want the source code look reading clear. three variables are shared inside one variable. I manipulate to change 8-bit data before it causes to change 16-bit data and 32-bit data. For example. union {
3
12525
by: rajatamilarasu | last post by:
for(i=0 ; i<listNum ; i++) { checker.checkN1DisagreementSwitch(pRep_Active_SList.ChassisID, pRep_Active_SList.SlotID, pRep_Standby_SList.ChassisID, pRep_Standby_SList.SlotID); } hi, i m getting the error "error C2227: left of '->ChassisID' must point to class/struct/union/generic type", when i try to compile the above code in my project. The object(pRep_Active_SList) which is accessing the structure member...
0
9566
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9393
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
10153
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9832
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...
1
7371
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6646
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
5272
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...
1
3921
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
3530
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.