Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++: Packing or padding data in a struct

Tags:

c++

c

padding

I'm using the Code::Blocks IDE with the GNU GCC compiler.

struct test
{
    char a;
    char e;
    char f;
    char b;
    char d;
};

sizeof(test) returns 5.

I read this answer: Why isn't sizeof for a struct equal to the sum of sizeof of each member?

How come there is no padding after the last char, so that sizeof(test) returns 6 or 8? There are a ton more questions I could ask once I add short and int, etc. But I think this question is good for now. Would not padding make it easier for the processor to work with the struct?

like image 480
newprogrammer Avatar asked Apr 01 '12 20:04

newprogrammer


People also ask

What is the difference between structure padding and packing?

padding makes things bigger. packing makes things smaller.

Why do structs need padding?

The answer to that lies in how a CPU accesses memory. Typically a CPU has alignment constraints, e.g. a CPU will access one word at a time, or a CPU will require data to be 16byte aligned, etc. So to make sure that data is aligned according to the constraints of the CPU, padding is required.

Are C structs padded?

Structure Padding in C:The structure padding is automatically done by the compiler to make sure all its members are byte aligned. Here 'char' is only 1 byte but after 3 byte padding, the number starts at 4 byte boundary. For 'int' and 'double', it takes up 4 and 8 bytes respectively.

What is the advantage of structure padding in C?

Padding increases the performance of the processor at the penalty of memory. In structure or union data members are aligned as per the size of the highest bytes member to prevent the penalty of performance.


1 Answers

The alignment of a char is only 1, so there is no need for the struct to be padded out to meet a larger alignment requirement.

like image 148
Puppy Avatar answered Nov 09 '22 21:11

Puppy