Перейти к содержимому

Structure padding что это

  • автор:

padding

Свойство padding устанавливает внутренние отступы/поля со всех сторон элемента. Область отступов это пространство между содержанием элемента и его границей. Отрицательные значения не допускаются.

Свойство padding краткая форма записи свойств, чтобы не писать отдельное правило для каждой стороны ( padding-top , padding-right , padding-bottom , padding-left ).

  • padding-bottom (en-US): 0
  • padding-left : 0
  • padding-right : 0
  • padding-top (en-US): 0
  • padding-bottom (en-US): процент, как указан, или абсолютная длина
  • padding-left : процент, как указан, или абсолютная длина
  • padding-right : процент, как указан, или абсолютная длина
  • padding-top (en-US): процент, как указан, или абсолютная длина

Синтаксис

/* Применяется для всех 4 сторон */ padding: 1em; /* По вертикали | По горизонтали */ padding: 5% 10%; /* Сверху | По горизонтали | Снизу */ padding: 1em 2em 2em; /* Сверху | Справа | Снизу | Слева */ padding: 2px 1em 0 1em; /* Глобальные значения */ padding: inherit; padding: initial; padding: unset; 

Значения

Укажите одно, два, три или четыре следующих значения:

Устанавливает неотрицательный, фиксированный размер. Подробнее в разделе .

Относительно ширины родительского блока.

Structure Padding in C

JavaTpoint

Structure padding is a concept in C that adds the one or more empty bytes between the memory addresses to align the data in memory.

Let’s first understand the structure padding in C through a simple scenario which is given below:

Suppose we create a user-defined structure. When we create an object of this structure, then the contiguous memory will be allocated to the structure members.

In the above example, we have created a structure of type student. We have declared the object of this structure named as ‘stud1‘. After the creation of an object, a contiguous block of memory is allocated to its structure members. First, the memory will be allocated to the ‘a‘ variable, then ‘b‘ variable, and then ‘c‘ variable.

What is the size of the struct student?

Now, we calculate the size of the struct student. We assume that the size of the int is 4 bytes, and the size of the char is 1 byte.

In the above case, when we calculate the size of the struct student, size comes to be 6 bytes. But this answer is wrong. Now, we will understand why this answer is wrong? We need to understand the concept of structure padding.

Structure Padding

The processor does not read 1 byte at a time. It reads 1 word at a time.

What does the 1 word mean?

If we have a 32-bit processor, then the processor reads 4 bytes at a time, which means that 1 word is equal to 4 bytes.

If we have a 64-bit processor, then the processor reads 8 bytes at a time, which means that 1 word is equal to 8 bytes.

Therefore, we can say that a 32-bit processor is capable of accessing 4 bytes at a time, whereas a 64-bit processor is capable of accessing 8 bytes at a time. It depends upon the architecture that what would be the size of the word.

Why structure padding?

If we have a 32-bit processor (4 bytes at a time), then the pictorial representation of the memory for the above structure would be:

Structure Padding in C

As we know that structure occupies the contiguous block of memory as shown in the above diagram, i.e., 1 byte for char a, 1 byte for char b, and 4 bytes for int c, then what problem do we face in this case.

What’s the problem?

The 4-bytes can be accessed at a time as we are considering the 32-bit architecture. The problem is that in one CPU cycle, one byte of char a, one byte of char b, and 2 bytes of int c can be accessed. We will not face any problem while accessing the char a and char b as both the variables can be accessed in one CPU cycle, but we will face the problem when we access the int c variable as 2 CPU cycles are required to access the value of the ‘c’ variable. In the first CPU cycle, the first two bytes are accessed, and in the second cycle, the other two bytes are accessed.

Suppose we do not want to access the ‘a’ and ‘b’ variable, we only want to access the variable ‘c’, which requires two cycles. The variable ‘c’ is of 4 bytes, so it can be accessed in one cycle also, but in this scenario, it is utilizing 2 cycles. This is an unnecessary wastage of CPU cycles. Due to this reason, the structure padding concept was introduced to save the number of CPU cycles. The structure padding is done automatically by the compiler. Now, we will see how structure padding is done.

How is structure padding done?

Structure Padding in C

In order to achieve the structure padding, an empty row is created on the left, as shown in the above diagram, and the two bytes which are occupied by the ‘c’ variable on the left are shifted to the right. So, all the four bytes of ‘c’ variable are on the right. Now, the ‘c’ variable can be accessed in a single CPU cycle. After structure padding, the total memory occupied by the structure is 8 bytes (1 byte+1 byte+2 bytes+4 bytes), which is greater than the previous one. Although the memory is wasted in this case, the variable can be accessed within a single cycle.

Let’s create a simple program of structures.

In the above code, we have created a structure named ‘student‘. Inside the main() method, we declare a variable of student type, i.e., stud1, and then we calculate the size of the student by using the sizeof() operator. The output would be 8 bytes due to the concept of structure padding, which we have already discussed in the above.

Output

Structure Padding in C

Changing order of the variables

Now, we will see what happens when we change the order of the variables, does it affect the output of the program. Let’s consider the same program.

The above code is similar to the previous code; the only thing we change is the order of the variables inside the structure student. Due to the change in the order, the output would be different in both the cases. In the previous case, the output was 8 bytes, but in this case, the output is 12 bytes, as we can observe in the below screenshot.

Output

Structure Padding in C

Now, we need to understand «why the output is different in this case«.

  • First, memory is allocated to the char a variable, i.e., 1 byte.
    Structure Padding in C
  • Now, the memory will be allocated to the int b Since the int variable occupies 4 bytes, but on the left, only 3 bytes are available. The empty row will be created on these 3 bytes, and the int variable would occupy the other 4 bytes so that the integer variable can be accessed in a single CPU cycle.
    Structure Padding in C
  • Now, the memory will be given to the char c At a time, CPU can access 1 word, which is equal to 4 bytes, so CPU will use 4 bytes to access a ‘c’ variable. Therefore, the total memory required is 12 bytes (4 bytes +4 bytes +4 bytes), i.e., 4 bytes required to access char a variable, 4 bytes required to access int b variable, and other 4 bytes required to access a single character of ‘c‘ variable.
    Structure Padding in C

How to avoid the structure padding in C?

The structural padding is an in-built process that is automatically done by the compiler. Sometimes it required to avoid the structure padding in C as it makes the size of the structure greater than the size of the structure members.

We can avoid the structure padding in C in two ways:

Using #pragma pack(1) directive

In the above code, we have used the #pragma pack(1) directive to avoid the structure padding. If we do not use this directive, then the output of the above program would be 16 bytes. But the actual size of the structure members is 13 bytes, so 3 bytes are wasted. To avoid the wastage of memory, we use the #pragma pack(1) directive to provide the 1-byte packaging.

Output

Structure Padding in C

  • By using attribute

Output

Structure Padding in C

Next Topic C Union

Youtube

For Videos Join Our Youtube Channel: Join Now

Feedback

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Trending Technologies

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

С interview questions. Structure alignment in c

No alt text provided for this image

С interview questions. Structure alignment in c

And it is probably clear to everyone that if the size was calculated simply by adding the sizes of all the elements included in this structure, which in our case is 9 bytes, then no one would ask this question.

The correct answer is that the size of the structure is 16 bytes.

Note 1: All examples discussed in this article were run on the STM32F407 microcontroller and compiled by the GCC 10.3 compiler

Structure alignment

The fact is that for structures in c, the next rule works: the fields of the structure are aligned in memory along a boundary multiple of their own size. That is, 1-byte fields are not aligned, 2-byte fields are aligned to even positions, 4—byte fields are aligned to multiples of four, etc.

And then our structure actually has next view:

No alt text provided for this image

And only size of this structure we can calculate as adding the sizes of all the elements included in this structure (including the elements padding[1-7]).

So the compiler added 7 extra elements to our structure:

No alt text provided for this image

  • padding1 — added in order to align the b element to the half-word boundary (2 bytes).
  • padding2, padding3, padding4 — added to align the d element to the word boundary (4 bytes).
  • padding5, padding6, padding7 — added because the structure itself should also be aligned, because structures can be combined into an array and if these three bytes were not there, then the second element of the array stuct ExampleStruct arr[2] would start with an unaligned address (0x0D):

Structure packing

So we saw that the compiler adds alignment, but can this be avoided if necessary? Such a need may arise in at least 2 cases:

  • In case if we need decrease memory consumption. Since when you refuse to align the structure, the paddings between the elements disappear, then, accordingly, it will take up less space in memory.
  • If you want the location of data in memory to exactly match the requirements of some low-level protocol or hardware.

In the both cases, you can get rid of the alignment of the elements of the structure and this is done by packing its elements. There are two types of it: manual and using the compiler directive.

Manual structure packing

With this packaging, it is necessary to redistribute the elements of the structure by yourself in such a way as to get rid of the empty elements that the compiler adds as much as possible. In our example, if the last element of the structure e is moved to the second place, then the element padding1 disappears. If the element d is swapped with c, then the elements padding2, padding3, padding4 will disappear, and the size of the structure will become 12 bytes, instead of 16 bytes:

No alt text provided for this imageNo alt text provided for this image

But in order not to engage in such fine-tuning every time, smart people have deduced a simple rule: arrange the elements of the structure in descending order of their size:

No alt text provided for this imageNo alt text provided for this image

This type of packaging, in addition to requiring manual adjustment, has another drawback: it could not provide maximum packaging in some cases. After all, in our example, the fields: padding5, padding6, padding7 still remained in the structure. To get rid of them, you need to use the following type of packaging method.

Structure packing by using compiler directive

In this case the special GCC compiler directive was used: #pragma pack:

No alt text provided for this image

This directive forces the compiler to refuse alignment and stack all the elements of the structure sequentially one after another. By using this directive you can get the minimum size of the structure — 9 bytes:

No alt text provided for this imageNo alt text provided for this image

Why do compiler need to align structures?

Well, there are two reasons: acceleration of access to structure elements, avoiding HardFault/MemFault on some processor architectures.

Acceleration of access to structure elements

The fact is that usually access to aligned variables is faster than to unaligned ones. Let ‘s look at the example of writing to elements of an aligned and unaligned structure:

No alt text provided for this image

For write to the aligned structure, the compiler generates the following code:

No alt text provided for this image

And to write to an unaligned structure:

No alt text provided for this image

As you can see, the assembler code for these two cases is identical except for the part of working with the unaligned element .b.

When working with this element, the compiler is forced to use two strb commands to write the highest and lowest byte instead of one assembler command to write a half-word: strh . And at the same time use the commands of the logical operation OR-NOT.

That is, instead of 3 instructions, we got 7. Accordingly, the dependence is simple: the more processor instructions to access an element of the structure, the more time this access takes.

However, the code that increases the number of instructions is generated by the compiler, but for many processor architectures this is unnecessary, because they fully support read/write operations of unaligned data in one instruction. For example, the Armv7 architecture processor (Cortex M3, M4, and M7) is available writing the variable uint16_t to an unaligned address with a single command strh.

According to the ARMv7-M Architecture Reference Manual:

The following data accesses support unaligned addressing, and only generate alignment faults when the CCR.UNALIGN_TRP bit is set to 1, see Configuration and Control Register, CCR on page B3-660:

Non halfword-aligned LDRH and STRH.

Non halfword-aligned TBH.

Non word-aligned LDR and STR.

According information above I had a question: is it possible to somehow force the compiler to generate more optimal code for such architectures? I haven’t found the answer yet, but if any of the dear readers knows the answer, then I would be grateful if you share it with me.

Note 2: In addition to increasing the number of instructions for writing an unaligned value, the presence of two write commands for the highest and lowest bytes turns the operation of writing a value to the .b element into a non-atomic operation.

HardFault/MemFault avoid

On some architectures, access to unaligned memory can not only slow down the program a little, but also cause an exception (MemoryFault/HardFault). Such architectures include, for example, ARMV6m (Cortex M0, M0+). So, if you are writing firmware for such architectures, then using the packaging method of the compiler directive is strictly contraindicated for you.

Structure Padding

I know compiler does Structure padding because CPU can read one word at time ( Word size depends on architecture 16/32/64 ) but I am not able to understand padding behavior for below example.

struct pad < char ch; >; 

Size of «struct pad» comes as 1 Byte ( But According to padding concept I suspected 4 byte ( 32 bit architecture ).

Nishith Goswami
asked Apr 23, 2015 at 4:38
Nishith Goswami Nishith Goswami
353 5 5 silver badges 13 13 bronze badges

I guess you are talking about the word boundary . On 32 bit systems boundary is 4 bytes and on 64 bit it is 8 bytes.

Apr 23, 2015 at 4:40
Yes exactly but in example above size comes as 1 Byte that is my doubt.
Apr 23, 2015 at 4:42
geeksforgeeks.org/… . have look @ this .
Apr 23, 2015 at 4:42

There is no need for padding. Padding wil be there between a char and int, or short and long, for example. By default, struct members are placed aligned according to platform ABI, and then padding appears. E.g. sizeof(int+char)==5, sizeof(char+int)==8.

Apr 23, 2015 at 4:49

6 Answers 6

A char type can be accessed efficiently on any address boundary, so no padding is necessary.

answered Apr 23, 2015 at 4:45
Michael Burr Michael Burr
334k 50 50 gold badges 536 536 silver badges 762 762 bronze badges
even this char type size is two bytes ?
– user6398437
Aug 4, 2018 at 3:31

First, it’s rather a compiler, not a CPU who adds padding—however the compiler adds padding respective to the specific target CPU capabilities (mostly to its data bus width).

Padding bytes are added for efficient memory access. When CPU reads or writes a 2-byte word on an even address through a 16-bit bus the transfer can be done in one cycle. However if 2-byte data is located at an odd address, it occupies a ‘lower’ half of one even-addressed word and an ‘upper’ half of another even-addressed word in memory. CPU then must perform two bus cycles: one for each memory word occupied by your data, each time utilizing only half the bus width for actual transfer.

For a 32-bit bus a 2-byte or 4-byte piece of data can also require two cycles if it spans across the double word (4-byte) boundary. Similar effects happen on 64-bit bus. That’s why the padding: a compiler adds bytes to align data to the boundaries where they can be efficiently accessed.

Padding may happen if a shorter member is followed by a longer one.

A structure containing 1-byte members only

struct BBB

doesn’t need any padding — each byte can be read or written in one cycle.
Similary

struct III

provided the structure is aligned to the even boundary (according to its first member requirement) all members are properly aligned, too.

struct BI < byte b; // one byte added here int i; >

Here one byte is added so that the 2-byte int is aligned to 2-bytes boundary.

struct IB < int i; byte b; // one byte added here >

Surprise! Why the additional byte at the end? What data needs aligning here.
Well, suppose you declare an array:

struct IB arr[4]; 

Then the array data is arranged in memory like this:

int arr[0].i byte arr[0].b // byte arr[0] padding int arr[1].i byte arr[1].b // byte arr[1] padding int arr[2].i byte arr[2].b // byte arr[2] padding int arr[3].i byte arr[3].b // byte arr[3] padding 

Every byte member at the end of the structure got ‘extendend’ to two bytes, so that the int in the next array item is aligned to an even address. Without padding every second array item would have its int member misaligned.

For a 32-bit bus up to 3 bytes of padding may be used:

struct BL < byte b; // 3 bytes added long l; >

so that 4-bytes long is placed at 4-bytes boundary.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *