Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why padding is not happening in this case?

As per my knowledge, By default 4-byte alignment will be done. say

typedef struct
{
     int data7;  
     unsigned char data8;
     //3 -bytes will be added here.
}Sample1;

so sizeof(Sample1) will be 8.

But for the following structure, why padding is not happened?.

typedef struct
{
     unsigned char data1;
     unsigned char data2;
     unsigned char data3;
     unsigned char data4;
     unsigned char data5;
     unsigned char data6;

}Sample2;

But the sizeof(Sample2) is 6 only. This Sample2 is not a 4 byte aligned structure?

EDIT::

As per Wiki

Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.

But members of Sample2 will not be aligned in multiples of two right??

Thanks.

like image 792
Jeyaram Avatar asked Aug 02 '12 07:08

Jeyaram


People also ask

Why is padding required?

The primary use of padding with classical ciphers is to prevent the cryptanalyst from using that predictability to find known plaintext that aids in breaking the encryption. Random length padding also prevents an attacker from knowing the exact length of the plaintext message.

Why does compiler insert padding?

The compiler will insert a padding byte after the char to ensure short int will have an address multiple of 2 (i.e. 2 byte aligned).


4 Answers

None of the fields in your second struct require 4-byte alignment. unsigned char only needs 1-byte alignment. Therefore, there is no need to actually align it to 4 bytes.

Structs are generally only aligned to the maximum alignment of all the fields.

like image 195
Mysticial Avatar answered Oct 11 '22 14:10

Mysticial


data7 is a 4-byte item, so the compiler will normally attempt to align it to an address that's a multiple of 4.

data1 is a one-byte item, so the compiler won't try to align it to any particular boundary (i.e., there would be no real gain from doing so).

like image 38
Jerry Coffin Avatar answered Oct 11 '22 14:10

Jerry Coffin


No, in a typical implementation Sample2 is not a 4-bute aligned structure. It is a 1-byte aligned structure.

In a typical implementation, the alignment requirement of the whole structure is calculated as the maximum of the alignment requirement of its individual members. This is why your Sample1 has alignment requirement of int (4 on your platform), and your Sample2 has alignment requirement of unsigned char, which is 1.

like image 41
AnT Avatar answered Oct 11 '22 13:10

AnT


Char requires 1 byte alignment. The max data type there is char , which is one byte alignment hence you are getting the size as '6'.

You can check this site for more understanding. http://www.geeksforgeeks.org/archives/9705. They have explained it in detail.

like image 21
Angus Avatar answered Oct 11 '22 15:10

Angus