473,779 Members | 2,072 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

padding mechanism in structures

Hello, All!

Could you please explain me how is the padding of 'structure' fields is
made?

For example:

struct {
char a1;
int a2;
double a3;
} str;

When I'm checking "sizeof str" in GCC compiler I get the value of size as
16, it means some bytes are padded right?

Thanks!

PS. Or, point me to Inet link, if there is one.

With best regards, Roman Mashak. E-mail: mr*@tusur.ru
Nov 14 '05 #1
10 2465
see if this helps with sample code attachment
pack
#pragma pack( [ n] )

Specifies packing alignment for structure and union members. Whereas the
packing alignment of structures and unions is set for an entire translation
unit by the /Zp option, the packing alignment is set at the data-declaration
level by the pack pragma. The pragma takes effect at the first structure or
union declaration after the pragma is seen; the pragma has no effect on
definitions.

When you use #pragma pack(n), where n is 1, 2, 4, 8, or 16, each structure
member after the first is stored on the smaller member type or n-byte
boundaries. If you use #pragma pack without an argument, structure members
are packed to the value specified by /Zp. The default /Zp packing size is
/Zp8.

The compiler also supports the following enhanced syntax:

#pragma pack( [ [ { push | pop}, ] [ identifier, ] ] [ n ] )

This syntax allows you to combine program components into a single
translation unit if the different components use pack pragmas to specify
different packing alignments.

Each occurrence of a pack pragma with a push argument stores the current
packing alignment on an internal compiler stack. The pragma's argument list
is read from left to right. If you use push, the current packing value is
stored. If you provide a value for n, that value becomes the new packing
value. If you specify an identifier, a name of your choosing, the identifier
is associated with the new packing value.

Each occurrence of a pack pragma with a pop argument retrieves the value at
the top of an internal compiler stack and makes that value the new packing
alignment. If you use pop and the internal compiler stack is empty, the
alignment value is that set from the command-line and a warning is issued.
If you use pop and specify a value for n, that value becomes the new packing
value. If you use pop and specify an identifier, all values stored on the
stack are removed from the stack until a matching identifier is found. The
packing value associated with the identifier is also removed from the stack
and the packing value that existed just before the identifier was pushed
becomes the new packing value. If no matching identifier is found, the
packing value set from the command line is used and a level-one warning is
issued. The default packing alignment is 8.

The new, enhanced functionality of the pack pragma allows you to write
header files that ensure that packing values are the same before and after
the header file is encountered:

/* File name: include1.h
*/
#pragma pack( push, enter_include1 )
/* Your include-file code ... */
#pragma pack( pop, enter_include1 )
/* End of include1.h */
In the previous example, the current pack value is associated with the
identifier enter_include1 and pushed, remembered, on entry to the header
file. The pack pragma at the end of the header file removes all intervening
pack values that may have occurred in the header file and removes the pack
value associated with enter_include1. The header file thus ensures that the
pack value is the same before and after the header file.

The new functionality also allows you to use code, such as header files,
that uses pack pragmas to set packing alignments that differ from the
packing value set in your code:

#pragma pack( push, before_include1 )
#include "include1.h "
#pragma pack( pop, before_include1 )
In the previous example, your code is protected from any changes to the
packing value that might occur in include.h.


Nov 14 '05 #2

Le 15/06/2005 13:53, dans d8***********@r elay.tomsk.ru, «*Roman Mashak*»
<mr*@tusur.ru > a écrit*:
Hello, All!

Could you please explain me how is the padding of 'structure' fields is
made?

For example:

struct {
char a1;
int a2;
double a3;
} str;

When I'm checking "sizeof str" in GCC compiler I get the value of size as
16, it means some bytes are padded right?

Thanks!

PS. Or, point me to Inet link, if there is one.

With best regards, Roman Mashak. E-mail: mr*@tusur.ru


It is probably architecture-dependant (and compiler-dependant), but
probably the double needs 8 bytes alignment, and the int needs 4 bytes, so:

A1 xx xx xx
A2 A2 A2 A2
A3 A3 A3 A3
A3 A3 A3 A3

Nov 14 '05 #3
On Wed, 15 Jun 2005 14:11:40 +0200, Mehta Shailendrakumar wrote:
see if this helps with sample code attachment
pack
#pragma pack( [ n] )
Note that the C language doesn't define a preprocessor directive called
#pragma pack. You compiler may provide one as an extension but you can't
assume that it will exist on other compilers or if it does it will act in
the same way.
Specifies packing alignment for structure and union members. Whereas the
packing alignment of structures and unions is set for an entire
translation unit by the /Zp option,
Again, compiler options are inherently compiler specific. Your compiler
might support such an option but you can't assume that others will. In
particular the original poster's compiler probably doesn't.
the packing alignment is set at the
data-declaration level by the pack pragma. The pragma takes effect at
the first structure or union declaration after the pragma is seen; the
pragma has no effect on definitions.
Since neither of these are C language features they aren't particularly
relevant to comp.lang.c. Also the question was more about how padding
works than how you might control it. In standard, portable C you can't.
When you use #pragma pack(n), where n is 1, 2, 4, 8, or 16, each
structure member after the first is stored on the smaller member type or
n-byte boundaries. If you use #pragma pack without an argument,
structure members are packed to the value specified by /Zp. The default
/Zp packing size is /Zp8.

The compiler also supports the following enhanced syntax:


Again, you mean *your* compiler. Usually the best thing to do with things
like #pragma pack is avoid them studiously since they are inherently
non-portable.

Lawrence
Nov 14 '05 #4
Hello Lawrence,

I have fwded gcc compiler specific info.
Can you suggest portable way to control padding?
Thanks.

Regards,
Shailendra

"Lawrence Kirby" <lk****@netacti ve.co.uk> wrote in message
news:pa******** *************** *****@netactive .co.uk...
On Wed, 15 Jun 2005 14:11:40 +0200, Mehta Shailendrakumar wrote:
see if this helps with sample code attachment
pack
#pragma pack( [ n] )


Note that the C language doesn't define a preprocessor directive called
#pragma pack. You compiler may provide one as an extension but you can't
assume that it will exist on other compilers or if it does it will act in
the same way.

Nov 14 '05 #5
Hello, Jean-Claude!
You wrote on Wed, 15 Jun 2005 14:33:52 +0200:

??>> size as 16, it means some bytes are padded right? Thanks! PS. Or,
??>> point me to Inet link, if there is one. With best regards, Roman
??>> Mashak. E-mail: mr*@tusur.ru

JCA> It is probably architecture-dependant (and compiler-dependant), but
JCA> probably the double needs 8 bytes alignment, and the int needs 4
JCA> bytes, so:
You mean when allocating memory for srtuct it acts like that (for my example
& GCC compiler, x86 architecture):

'char a1' occupies 1 byte
'int a2' occupies 4 bytes
'double a3' ~ 8 bytes

totally -> 13 bytes, sizeof str = 16 bytes. Seems like 3 bytes are taken
after 'char a1' alignment to int ?

With best regards, Roman Mashak. E-mail: mr*@tusur.ru
Nov 14 '05 #6

Le 15/06/2005 15:44, dans d8***********@r elay.tomsk.ru, «*Roman Mashak*»
<mr*@tusur.ru > a écrit*:
Hello, Jean-Claude!
You wrote on Wed, 15 Jun 2005 14:33:52 +0200:

??>> size as 16, it means some bytes are padded right? Thanks! PS. Or,
??>> point me to Inet link, if there is one. With best regards, Roman
??>> Mashak. E-mail: mr*@tusur.ru

JCA> It is probably architecture-dependant (and compiler-dependant), but
JCA> probably the double needs 8 bytes alignment, and the int needs 4
JCA> bytes, so:
You mean when allocating memory for srtuct it acts like that (for my example
& GCC compiler, x86 architecture):

'char a1' occupies 1 byte
'int a2' occupies 4 bytes
'double a3' ~ 8 bytes

totally -> 13 bytes, sizeof str = 16 bytes. Seems like 3 bytes are taken
after 'char a1' alignment to int ?

With best regards, Roman Mashak. E-mail: mr*@tusur.ru


Yes that's what I mean: 3 bytes after the char.
Usually variables are aligned "on their size", but you
should make tests or read the documentation of GCC,
or even the ABI for x86. In fact I checked, and with
my gcc/PowerPC, doubles are aligned on 4 bytes only,
whereas the ABI says the natural alignment is 8 bytes.
you can have a look here, but it's for PPC/68K only.
At least it shows what it could resemble on x86.

http://developer.apple.com/documenta...tual/PowerPCRu
ntime/Data/chapter_2_secti on_3.html

Nov 14 '05 #7
Mehta Shailendrakumar wrote:
.... snip ...
The new functionality also allows you to use code, such as header
files, that uses pack pragmas to set packing alignments that differ
from the packing value set in your code:

#pragma pack( push, before_include1 )
#include "include1.h "
#pragma pack( pop, before_include1 )

In the previous example, your code is protected from any changes
to the packing value that might occur in include.h.

Name: pack.c
pack.c Type: Textpad File (application/x-unknown-content-type-cfile)
Encoding: x-uuencode


Never attach anything to a usenet article, especially a binary.
This is a text only medium.

In addition, pragma is not sanctioned by the standard. From N869:

[#1] A preprocessing directive of the form

# pragma pp-tokens-opt new-line

where the preprocessing token STDC does not immediately
follow pragma in the directive (prior to any macro
replacement)136 ) causes the implementation to behave in an
implementation-defined manner. The behavior might cause
translation to fail or cause the translator or the resulting
program to behave in a non-conforming manner. Any such
pragma that is not recognized by the implementation is
ignored.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #8
On Wed, 15 Jun 2005 15:34:34 +0200, Mehta Shailendrakumar wrote:
Hello Lawrence,

I have fwded gcc compiler specific info.
Can you suggest portable way to control padding?

C provides no method to control padding i.e. alignment of structure
members. If you need an exact format e.g. an external data format then you
shoudln't be trying to map a structure onto it. Indstead treat your
external data as a sequence of bytes and write marshalling./unmarshalling
code to convert between that and an internal representation, e.g. a normal
structure.

In general when you ask about "controllin g padding" you're asking the
wrong question, you need to take a higher level look at what it is you are
trying to do.

Lawrence

Nov 14 '05 #9
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Roman Mashak wrote:
Hello, All!

Could you please explain me how is the padding of 'structure' fields is
made?

For example:

struct {
char a1;
int a2;
double a3;
} str;

When I'm checking "sizeof str" in GCC compiler I get the value of size as
16, it means some bytes are padded right?
It could.

It could also mean that
(sizeof(int) == 5) and
(sizeof(double) == 10)

But i doubt it.
Thanks!

PS. Or, point me to Inet link, if there is one.

With best regards, Roman Mashak. E-mail: mr*@tusur.ru

- --
Lew Pitcher

Master Codewright & JOAT-in-training | GPG public key available on request
Registered Linux User #112576 (http://counter.li.org/)
Slackware - Because I know what I'm doing.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFCsOSZagV FX4UWr64RAvlJAJ wMrq9DGOomZlP2D 4oG89XgdlYTagCg iaAl
lgGLNcuefrDQpQC 8sa/n5W8=
=hVwW
-----END PGP SIGNATURE-----
Nov 14 '05 #10

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

Similar topics

13
3894
by: Amarendra | last post by:
Folks, This structure padding issue is bothering me now, could not locate a satisfactory answer on clc, so here it goes... I have a structure, given below: typedef struct { int flag; char keys; char padding;
28
20803
by: ramu | last post by:
Hi all, I understand that some compilers pad some bytes to the aggregate data types in order to access the members of the aggregate data types(i.e. structure) fast. This depends on the architectures. Some architectures cannot access the data which will be stored on the odd addresses or they may find difficult to access it. This is the reason for padding extra bytes. Now consider the following structure:
20
2323
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
36
3052
by: phil-news-nospam | last post by:
Here is a simpler (no drop shadows) example of the padding bug I see: http://phil.ipal.org/usenet/ciwas/2006-05-08/buttons-1.html So far I find nothing in the CSS2 document that says I should get this kind of inconsistent result. -- ----------------------------------------------------------------------------- | Phil Howard KA9WGN | http://linuxhomepage.com/ http://ham.org/ |
3
5165
by: abhivg | last post by:
Hi, I am trying to port a 32 bit Unix application to 64 bit Windows. While compiling on Windows I am getting a number of warnings related to structure padding. More specifically "warning C4820: 'seqargs' : '4' bytes padding added after data member 'stop_codon_pos'" Assuming that there is no pointer arithmetic being done on these structures, is it ok to safely ignore this warning?
10
3293
by: Rohit kumar Chandel | last post by:
Hi All, Please let me know how to find in a structure whether compiler has used padding or not. Regards Rohit
3
1772
by: Martin | last post by:
Is clearing a structure the following way well defined in C89? The structure ACTION contains no floating point or pointer members. Only integral types. My thoughts concern the padding - can and should it be altered? typedef unsigned char Byte; #define MAX_ACTIONS 10 /* ... */
13
3059
by: aarklon | last post by:
Hi all, arrays are guaranteed to be contiguous with no padding before or after any array member , but what about enums ..???
3
3539
by: vikas talwar | last post by:
Hi All, Can you please explain me how the 'C' compiler allocate memory to 'struct'. Please go thu the example below and pls suggest me the solution for my problem. Here is my structure definition struct my_dev {
0
9636
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
9474
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
10306
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...
1
10075
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9931
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
8961
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5373
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
4037
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
3
2869
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.