473,770 Members | 6,515 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

struct memory padding

I'm taking an intro course on C++, and our teacher is not being
clear on how stuct memory padding is determined.

If the memory used by all components defined inside a struct
falls between a certain gradient, a struct "rounds up" to the
nearest multiple of the gradient.

This teacher is somewhat erratic and has said on subsequent days
that first the padding is rounded up to nearest multiple of 4,
and then the nearest power of 2.

I reading on my own, it looks like the padding of the struct is
determined by the word size fo the platform, which I assume means
multiples of 16.

Could someone well-versed in C++ please point out how this is
done?

Cheers,
Simon

--
Stupendous Tales
www.stupendoustales.com
Speculative Fiction, Pulp Dreams
Jan 22 '07 #1
11 3639
si****@nospam.c om wrote:
I'm taking an intro course on C++, and our teacher is not being
clear on how stuct memory padding is determined.

If the memory used by all components defined inside a struct
falls between a certain gradient, a struct "rounds up" to the
nearest multiple of the gradient.

This teacher is somewhat erratic and has said on subsequent days
that first the padding is rounded up to nearest multiple of 4,
and then the nearest power of 2.

I reading on my own, it looks like the padding of the struct is
determined by the word size fo the platform, which I assume means
multiples of 16.

Could someone well-versed in C++ please point out how this is
done?
While not defined by the standard, padding tends to be to the natural
alignment of the processor So on a 32 bit processor, the struct

struct X {
char a;
int b;
};

will have a size of 8 with three padding bytes after 'a'.

Some platforms support packing to eliminate padding, but this is
non-standard and impossible on some processors.

--
Ian Collins.
Jan 22 '07 #2
Hope this helps you
http://www.thescripts.com/forum/thread543879.html
si****@nospam.c om wrote:
I'm taking an intro course on C++, and our teacher is not being
clear on how stuct memory padding is determined.

If the memory used by all components defined inside a struct
falls between a certain gradient, a struct "rounds up" to the
nearest multiple of the gradient.

This teacher is somewhat erratic and has said on subsequent days
that first the padding is rounded up to nearest multiple of 4,
and then the nearest power of 2.

I reading on my own, it looks like the padding of the struct is
determined by the word size fo the platform, which I assume means
multiples of 16.

Could someone well-versed in C++ please point out how this is
done?

Cheers,
Simon

--
Stupendous Tales
www.stupendoustales.com
Speculative Fiction, Pulp Dreams
Jan 22 '07 #3
Thanks so much. Padding of the struct will bring it up to the
next multiple of the word size, eg. 32bit/4byte

Cheers,
Simon

--
Stupendous Tales
www.stupendoustales.com
Speculative Fiction, Pulp Dreams
Jan 22 '07 #4
Yahooooooooo wrote:
Hope this helps you
http://www.thescripts.com/forum/thread543879.html

Please don't top-post.

--
Ian Collins.
Jan 22 '07 #5
si****@nospam.c om wrote:
I'm taking an intro course on C++, and our teacher is not being
clear on how stuct memory padding is determined.

If the memory used by all components defined inside a struct
falls between a certain gradient, a struct "rounds up" to the
nearest multiple of the gradient.

This teacher is somewhat erratic and has said on subsequent days
that first the padding is rounded up to nearest multiple of 4,
and then the nearest power of 2.

I reading on my own, it looks like the padding of the struct is
determined by the word size fo the platform, which I assume means
multiples of 16.

Could someone well-versed in C++ please point out how this is
done?
While padding is specifically allowed in the
C++ standard, it is not specified. It in implementation dependant.

In general, however, the implementations of padding is fairly uniform.

Each member of a struct has an "alignment" which is implementation
defined. The alignment of various types is sometimes mandatory (like in
RISC processors - MIPS, PowerPC, SPARC) and sometimes and optimization
(e.g. IA32, AMD64).

The resulting alignment of a struct is the alignment of the member(s)
with the largest alignment.

e.g.

struct X { char a; char b; }; // has alignment of char

struct Y { char a; int b; short c; }; // has alignment of int

Padding is added between members to guarentee that the offset of all
members in the struct falls on a multiple of the alignment.

e.g.
if alignment of :

char is 1
long long is 8

then

struct Z
{
char a;
// padding added here (7 bytes)
long long b; // offset is 8
};

sizeof Z is 16
alignment of Z is 8

.....

While that is the basic implementation, the actual alignments for each
type varies between platforms and sometimes on different "architectu res"
or ABI's on each platform. For example, on MIPS o32, alignment of
double is 4 while on MIPS n32, alignment of double is 8 (IIRC).

It's really not all that hard.
Jan 22 '07 #6
<si****@nospam. comwrote in message news:ep******** **@reader2.pani x.com
I'm taking an intro course on C++, and our teacher is not being
clear on how stuct memory padding is determined.

If the memory used by all components defined inside a struct
falls between a certain gradient, a struct "rounds up" to the
nearest multiple of the gradient.

This teacher is somewhat erratic and has said on subsequent days
that first the padding is rounded up to nearest multiple of 4,
and then the nearest power of 2.

I reading on my own, it looks like the padding of the struct is
determined by the word size fo the platform, which I assume means
multiples of 16.

Could someone well-versed in C++ please point out how this is
done?
The C++ standard makes no rules on this. It depends on the platform and is
sometimes controllable using compiler switches. It can also vary with the
order of declaration of variables.

Using VC++ on Windows, you can eliminate all padding if you want. By
default, a struct is rounded up to a multiple of its largest data member,
but still leaves a possible role for the order of declaration, e.g.,

struct X1
{
char ch1;
int x1;
char ch2;
int x2;
};

has a size of 16. However, the following struct, with the same members in a
different order, has a size of 12.

struct X2
{
char ch1;
char ch2;
int x1;
int x2;
};

The reason that X1 is larger is because the two ints are aligned on 4 byte
boundaries, so there are 3 bytes after each char. With X2, by contrast, you
only need 2 bytes after ch2 to achieve alignment of the ints on 4 byte
boundaries.

Read up the documentation for the compiler you are interested in to see how
it is handled.

--
John Carson
Jan 22 '07 #7
<si****@nospam. comwrote in message
news:ep******** **@reader2.pani x.com...
: I'm taking an intro course on C++, and our teacher is not being
: clear on how stuct memory padding is determined.
:
: If the memory used by all components defined inside a struct
: falls between a certain gradient, a struct "rounds up" to the
: nearest multiple of the gradient.
:
: This teacher is somewhat erratic and has said on subsequent days
: that first the padding is rounded up to nearest multiple of 4,
: and then the nearest power of 2.
:
: I reading on my own, it looks like the padding of the struct is
: determined by the word size fo the platform, which I assume means
: multiples of 16.
:
: Could someone well-versed in C++ please point out how this is
: done?

[ keep in mind that everything related to padding is architecture-
dependent, and not something specified in the C++ standard ]

Padding is dependent on the alignment requirements of the data
members (or fields) of the struct.
For example:
struct FiveChars { char a,b,c,d,e; };
often does not have any padding (neither between members,
nor at the end of the struct): sizeof(FiveChar s)==5
Here's how I would summarize things:

The alignment requirement of a data member normally is a
power of two, usually up to the largest word size of the
target architecture.
For example: char<->1 short<->2 long<->4 long long<-4 or 8 ?
(but on a 16-bit architecture, 2 bytes might be the largest alignment
requirement, applying to all primitive types except (signed/u)char ).

Each data member is preceded by the padding required to align
itself properly relative to the beginning of the struct.

The size of the whole struct is padded so that it is a multiple
of the largest alignment requirement of its data fields.
I hope this helps --Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form

Jan 22 '07 #8
si****@nospam.c om wrote:
Thanks so much. Padding of the struct will bring it up to the
next multiple of the word size, eg. 32bit/4byte
There is no standard rule that will predict how a C++ compiler will
distribute padding bytes (if any) within a particular struct.

In fact, it would be a mistake to think that there is only alignment
convention per machine architecture. On the contrary, alignment
conventions tend to accumulate over time. Old ones never really go away
- because as soon as some struct with a particular alignment convention
is saved to a disk for the first time - then that alignment convention
will effectively be around forever. For example, C++ compilers on the
Macintosh recognized three different alignment conventions that exist
on that platform (68K, Power, "natural"). And most C++ compilers allow
a programmer to specify the size and location of a struct's padding
bytes themselves, just in case the conventional schemes are not enough.

Greg

Jan 22 '07 #9

si****@nospam.c om wrote:
Thanks so much. Padding of the struct will bring it up to the
next multiple of the word size, eg. 32bit/4byte

Cheers,
Simon

--
Stupendous Tales
www.stupendoustales.com
Speculative Fiction, Pulp Dreams
The statements in the link given in a previous post were not entirely
accurate. Basically, padding occurs because the underlying CPU either
requires or prefers a given alignment when reading/writing fundamental
types. This is not necesarrily the same size as the word size. One
example is the newer x86 processors where an optimal reading of doubles
requires the double to be aligned on an 8 byte boundary. Thus
struct s { char c; double d; } will most likely occupy 16 bytes.

/Peter

Jan 22 '07 #10

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

Similar topics

5
17653
by: Roy Hills | last post by:
When I'm reading from or writing to a network socket, I want to use a struct to represent the structured data, but must use an unsigned char buffer for the call to sendto() or recvfrom(). I have two questions: 1. Is it generally safe to "overlay" the structure on the buffer, e.g.: unsigned char buffer;
5
2392
by: Kobu | last post by:
In embedded systems (programmed in C), often times structure declarations are used to group together several status/control/data registers of external hardware (or even internal registers). The example below (from GBD's THE C BOOK) uses this. Is this a portable method? . /*
21
2527
by: hermes_917 | last post by:
I want to use memcpy to copy the contents of one struct to another which is a superset of the original struct (the second struct has extra members at the end). I wrote a small program to test this, and it seems to work fine, but are there any cases where doing something like this could cause any problems? Here's the small program I wrote to test this: #include <stdio.h>
5
4053
by: Hallvard B Furuseth | last post by:
Does struct assignment copy padding bytes? Some compilers do, but I couldn't find anything in the standard which says they must. What I need is for any padding bytes to contan initialized values before fwrite(), to shut up memory debuggers like Valgrind about writing uninitialized data to the file. Simplified code: static const struct S default_value = ...; struct S s, t;
8
3688
by: =?Utf-8?B?R2Vvcmdl?= | last post by:
Hello everyone, I heard when define a struct, it is important to make the size of the struct memory aligned. For example, struct foo
14
8845
by: barcaroller | last post by:
I have a multi-field struct and a memory block (created using malloc) that contains structured data. If I map the struct to the memory block, am I guaranteed that the struct fields will be filled properly or do I have to worry about the compiler padding the struct? Example: typedef struct { int16 field1; // 2 bytes
19
4780
by: rmr531 | last post by:
First of all I am very new to c++ so please bear with me. I am trying to create a program that keeps an inventory of items. I am trying to use a struct to store a product name, purchase price, sell price, and a taxable flag (a Y/N char) and then write this all out to a file (preferably just a plain old text file) and then read it in later so that I can keep a running inventory. The problem that I am running into is when I write to the...
6
5185
by: Francois Grieu | last post by:
Hello, I'm asking myself all kind of questions on allocating an array of struct with proper alignment. Is the following code oorrect ? I'm most interested by the statement t = malloc(n*sizeof(r)) and (to a degree) by the surrounding error checking.
3
3538
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
9592
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
10058
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
9870
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
8886
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...
1
7416
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
5450
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3972
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
3576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2817
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.