Behavior of the sizeof operator in C

I get unusual behavior with my code that looks like this

#include<stdio.h> struct a { int x; char y; }; int main() { struct a str; str.x=2; str.y='s'; printf("%d %d %d",sizeof(int),sizeof(char),sizeof(str)); getch(); return 0; } 

For this part of the code, I get the output:

 4 1 8 

As far as I know, the structure contains an integer variable of size 4 and a variable char of size 1, so the size of the structure a should be 5. But how will the size of the structure get 8. I use the C ++ visual compiler. Why is this behavior?

+6
source share
3 answers

It is called Structural Gasket.

The presence of data structures that begin with alignment by 4 bytes (on processors with 4 byte buses and processors) is much more efficient when moving data around memory and between RAM and CPU.

You can usually disable this using compiler options and / or pragmas, the features of this will depend on your particular compiler.

Hope this helps.

+12
source

The compiler inserts an add-on for optimization and agitation purposes. Here the compiler inserts 3 dummy bytes between (or after) your both members.

You can handle alignment using the #pragma .

+8
source

Basically, to illustrate how this add-on works, I slightly modified your program.

 #include<stdio.h> struct a { int x; char y; int z; }; int main() { struct a str; str.x=2; str.y='s'; str.z = 13; printf ( "sizeof(int) = %lu\n", sizeof(int)); printf ( "sizeof(char) = %lu\n", sizeof(char)); printf ( "sizeof(str) = %lu\n", sizeof(str)); printf ( "address of str.x = %p\n", &str.x ); printf ( "address of str.y = %p\n", &str.y ); printf ( "address of str.z = %p\n", &str.z ); return 0; } 

Notice that I added the third element to the structure. When I run this program, I get:

 amrith@amrith-vbox :~/so$ ./padding sizeof(int) = 4 sizeof(char) = 1 sizeof(str) = 12 address of str.x = 0x7fffc962e070 address of str.y = 0x7fffc962e074 address of str.z = 0x7fffc962e078 amrith@amrith-vbox :~/so$ 

Part of this, which illustrates the filling, is highlighted below.

 address of str.y = 0x7fffc962e074 address of str.z = 0x7fffc962e078 

As long as y is just one character, note that z is the full 4 bytes.

0
source

Source: https://habr.com/ru/post/914219/


All Articles