paperplan3
paperplan3

Reputation: 67

Memory allocation from struct in 64 bit system

I was going through old examns and found this question, where I have to put in field size and padding size for this specific struct on a 64 bit operating system:

struct mystruct {
    char a;
    uint32_t b;
    int16_t c;
    int64_t d;
};

The answer is:

struct mystruct {
    char a;     //field size: 1, padding size: 3
    uint32_t b; //field size: 4, padding size: 0
    int16_t c;  //field size: 2, padding size: 6
    int64_t d;  //field size: 8, padding size: 0
};

I do understand why int16_t gets allocated 2 Bytes and 6 padding, because of the 64 bit architecture. Same with int64_t.

But why is the char allocated with 3 padding size and uint32_t with field size of 4 when its a 64 Bit architecture ?

Upvotes: 2

Views: 391

Answers (1)

kiran Biradar
kiran Biradar

Reputation: 12732

struct mystruct {
    char a;     //field size: 1, padding size: 3
    uint32_t b; //field size: 4, padding size: 0
    int16_t c;  //field size: 2, padding size: 6
    int64_t d;  //field size: 8, padding size: 0
};

I do understand why int16_t gets allocated 2 Bytes and 6 padding, because of the 64 bit architecture. Same with int64_t. But why is the char allocated with 3 padding size and uint32_t with field size of 4 when its a 64 Bit architecture ?

Because:

  • char would start from any offset.

  • unit32_t would start from the offset mod(4) == 0.

  • int16_t would start from the offset mod(2) == 0.

  • int64_t would start from the offset mode(8) == 0.

thus

 offset  ->   0   1           4    8   10           16            24
              +--------------------+----------------+-------------+
              | a | 3byte pad |  b | c | 6byte pad  |   d         |
              +--------------------+----------------+-------------+

Upvotes: 3

Related Questions