Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sizeof() differs on 64bit cpu?

Tags:

c

Consider following example:

#include <stdio.h>
#include <inttypes.h>

struct A {
        uint32_t i1;
        uint32_t i2;
        uint32_t i3;
        uint64_t i4;
        uint32_t i5;
        uint32_t i6;
        uint32_t i7;
        uint64_t i8;
        uint32_t i9;
};

struct B {
        uint32_t i1;
        uint32_t i2;
        uint32_t i3;
        uint32_t i4;
        uint32_t i5;
        uint32_t i6;
        uint32_t i7;
        uint64_t i8;
        uint64_t i9;
};

int
main()
{
        struct A a;
        struct B b;

        printf("sizeof(a) = %u, sizeof(b) = %u\n", sizeof(a), sizeof(b));

        return 0;
}

Output is:

$ ./t2 
sizeof(a) = 56, sizeof(b) = 48
$ 

Why are they differ on 64bit machine ? On 32 bit platform results are the same:

$ ./t2
sizeof(a) = 44, sizeof(b) = 44
like image 662
Konstantin Avatar asked Jun 04 '09 16:06

Konstantin


People also ask

What is the return value of size of in 64-bit machine?

So, the sizeof(int) simply implies the value of size of an integer. Whether it is a 32-bit Machine or 64-bit machine, sizeof(int) will always return a value 4 as the size of an integer.

Is unsigned long long 64 bits?

Some properties of the unsigned long long int data type are: An unsigned data type stores only positive values. It takes a size of 64 bits. A maximum integer value that can be stored in an unsigned long long int data type is 18, 446, 744, 073, 709, 551, 615, around 264 – 1(but is compiler dependent).

Is unsigned long 32-bit or 64-bit?

LLP64 or 4/4/8 ( int and long are 32-bit, pointer is 64-bit)


1 Answers

Some diagrams to help you see:

32-bit:

+----+----+----+----+----+----+----+----+----+----+----+
| i1 | i2 | i3 |   i4    | i5 | i6 | i7 |   i8    | i9 | Struct A
+----+----+----+----+----+----+----+----+----+----+----+

+----+----+----+----+----+----+----+----+----+----+----+
| i1 | i2 | i3 | i4 | i5 | i6 | i7 |   i8    |   i9    | Struct B
+----+----+----+----+----+----+----+----+----+----+----+

64-bit:

+---------+---------+---------+---------+---------+---------+---------+
| i1 | i2 | i3 |~~~~|    i4   | i5 | i6 | i7 |~~~~|   i8    | i9 |~~~~| Struct A
+---------+---------+---------+---------+---------+---------+---------+

+---------+---------+---------+---------+---------+---------+
| i1 | i2 | i3 | i4 | i5 | i6 | i7 |~~~~|   i8    |   i9    | Struct B
+---------+---------+---------+---------+---------+---------+
  • + : address boundaries
  • ~ : padding
like image 82
Juliano Avatar answered Sep 19 '22 23:09

Juliano