Structure size and memory layout depending on #pragma package

Consider the following program compiled in VC ++ 2010:

#pragma pack(push, 1)    // 1, 2, 4, 8
struct str_test
{
    unsigned int n;
    unsigned short s;
    unsigned char b[4];
};
#pragma pack(pop)

int main()
{
    str_test str;
    str.n = 0x01020304;
    str.s = 0xa1a2;
    str.b[0] = 0xf0;
    str.b[1] = 0xf1;
    str.b[2] = 0xf2;
    str.b[3] = 0xf3;

    unsigned char* p = (unsigned char*)&str;
    std::cout << sizeof(str_test) << std::endl;
    return 0;
}

I set a breakpoint on the line return 0;and look in the memory window in the debugger, starting at the address p. I get the following results ( sizeofand memory layout, depending on pack):

// 1 - 10    (pack, sizeof)
// 04 03 02 01 a2 a1 f0 f1 f2 f3

// 2 - 10
// 04 03 02 01 a2 a1 f0 f1 f2 f3

// 4 - 12
// 04 03 02 01 a2 a1 f0 f1 f2 f3

// 8 - 12
// 04 03 02 01 a2 a1 f0 f1 f2 f3

Two questions:

  • Why sizeof(str_test)is 12 for package 8?

  • Why is the memory layout the same and independent of the value of the package?

+4
source share
1 answer

Why is sizeof (str_test) equal to 12 for package 8?

From MSDN Docs :

, n , , .

- 4 , 8, 4 .

?

, . 8 :

#pragma pack(push, 8)    // largest element is 4bytes so it will be used instead of 8
struct str_test
{
    unsigned int n; // 4 bytes
    unsigned short s; // 2 bytes        
    unsigned char b[4]; // 4 bytes
    //2 bytes padding here;
};
#pragma pack(pop)

sizeof (str_test) 12.

, , (MSVC2010) , unsigned char b[4]; . 2 cc cc .

#pragma pack(push, 8)    // largest element is 4bytes so it will be used instead of 8
struct str_test
{
    unsigned int n; // 4 bytes
    unsigned short s; // 2 bytes 
    //2 bytes padding here;       
    int;  // 4 bytes

};
#pragma pack(pop)

, , char[4] int 6 8 .

int

04 03 02 01 a2 a1 cc cc f0 f1 f2 f3

unsigned char[4]

04 03 02 01 a2 a1 f0 f1 f2 f3 cc cc
+3

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


All Articles