Strict data alignment

As far as I know, data alignment consists of placing data in 64-bit / 32-bit chunks in memory for processor performance, I use a 64-bit Linux machine, and I did some tests and got some weird results (I can't explain the behavior )

Here are the structures I used:

  class A {
    long l0,l1,l2;
  };

  class B {
    long l0,l1,l2,l3;
  };

  class C {
    long l0,l1,l2,l3,l4;
  };

test:

int main() {
    C* newC = new C();
    B* newB = new B();
    A* newA = new A();
    int* i = new int();

    std::cout << sizeof(A) << std::endl;
    std::cout << sizeof(B) << std::endl;
    std::cout << sizeof(C) << std::endl;

    std::cout << "C : " << newC << std::endl;
    std::cout << "B : " << newB << std::endl;
    std::cout << "A : " << newA << std::endl;
    std::cout << "i : " << i << std::endl;

    delete (i);
    delete (newC);
    delete (newA);
    delete (newB);

    return 0;
}

Just putting one object each in a heap, I added a pointer to the end to see the memory occupied newA

The result is the following:

24
32
40
C : 0x603010
B : 0x603040
A : 0x603070
i : 0x603090

3*16 bytesbetween address newCand newB: C - 40 bytes, which is already a multiple of 64 bits, why are these 8 bytes more?

3*16 bytesbetween newBand newA? B - only 32 bytes, I expected:A : 0x603060

2*16 bytesbetween the address newAand i??

+4
source
2

- , .

, , , :

+--------+-------------+--------+-------------+
| header | alloced mem | header | alloced mem | ...
+--------+-------------+--------+-------------+

, () ( , ). , .


, , :

#include <iostream>
#include <cstdlib>
int main (int argc, char *argv[]) {
    char *one = new char[std::atoi(argv[1])];
    char *two = new char[std::atoi(argv[1])];
    std::cout << static_cast<void*>(one) << '\n';
    std::cout << static_cast<void*>(two) << '\n';
    return 0;
}

script:

#!/usr/bin/bash
for i in {01..37}; do
    echo $i $(./qq $i)
done

:

01 0x800102e8 0x800102f8
02 0x800102e8 0x800102f8
:: (all the same address pairs in here and in gaps below)
12 0x800102e8 0x800102f8
13 0x800102e8 0x80010300
::
20 0x800102e8 0x80010300
21 0x800102e8 0x80010308
::
28 0x800102e8 0x80010308
29 0x800102e8 0x80010310
::
36 0x800102e8 0x80010310
37 0x800102e8 0x80010318

, .

, new char[12] , , , , + + .

, , , , , , , , . , , , .

, , x[0] x[1]. , , sizeof.

+4

, new .

, :

  struct D{
    C c;
    B b;
    A a;
  }

. , , .

+2

All Articles