C ++ memory superstructure in clang?

Is there any memory overhead for each structure in clang? Typically, the size of a structure is just the total size of all its members. But this is not like clang:

#include <iostream>
using namespace std;

struct Obj {
    int x;
    int y;
};

int main() {
    int a = 42;
    int b = 43;
    Obj obj = {100, 101};
    int c = 44;

    cout << *(&a - 0) << endl;  // 42
    cout << *(&a - 1) << endl;  // 43
    cout << *(&a - 2) << endl;  // On clang this prints garbage value instead of 101, how strange...
    cout << *(&a - 3) << endl;  // 101
    cout << *(&a - 4) << endl;  // 100
    cout << *(&a - 5) << endl;  // 44

    return 0;
}

I compiled with clang++ program.cpp, without optimization. Version:

Ubuntu clang version 3.4-1ubuntu3 (tags/RELEASE_34/final) (based on LLVM 3.4)
Target: x86_64-pc-linux-gnu
Thread model: posix

The memory location in (&a - 2)seems not to be used at all. I entered the following code between the declaration int aand int b:

*(&a - 2) = -1234;

This will later print -1234instead of the garbage value on *(&a - 2), indicating that clang did not write this value after creation Obj obj, which makes me wonder why the clang reserved it in the first place.

gcc -. -, , , gcc . , gcc , c b, :

cout << *(&a + 0) << endl;  // 42
cout << *(&a + 1) << endl;  // 43
cout << *(&a + 2) << endl;  // 44 gcc moved c here even without optimization
cout << *(&a + 3) << endl;  // 100
cout << *(&a + 4) << endl;  // 101

g++ program.cpp. :

 g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2

, C. 64- Linux Mint 17.1. - , , 4 ?

+4
4

, , , . undefined, , , , . - , . .

, , GCC, Clang, , ( ) Linux.

, , , , , . .

+2

Clang 8- , . GCC , GCC , .

+1

: . ( gcc/clang , ).

, , (& member% sizeof (member) == 0):

struct foo {
    char a;
    int b; // pad 3 bytes before b
}

. , sizeof (T)% sizeof ( T) == 0, :

struct foo {
    int a;
    char b; // pad 3 bytes after b
}

( a, b, obj c) , .

, , .

+1

, . 4 32- , 64-.

#pragma, :

#pragma pack(push)  /* push current alignment to stack */
#pragma pack(1)     /* set alignment to 1 byte boundary */

struct MyPackedData
{
    char Data1;
    long Data2;
    char Data3;
};

#pragma pack(pop)   /* restore original alignment from stack */

, , , . . x86?

. https://en.wikipedia.org/wiki/Data_structure_alignment.

I have no idea if this is so, because 2 ints should be aligned anyway, but maybe they are not on 64-bit architectures? Ints are 32-bit even for 64-bit CPUs, while alignment is probably 64-bit or 8 bytes.

Of course, since the structure is on the stack, other variables and their alignment also matter.

Also see C / C ++ Structure Alignment and Memory Alignment in C-structs

-1
source

All Articles