Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct members memory layout

Tags:

c++

c

If I have a struct like this:

struct S {
    ANY_TYPE a;
    ANY_TYPE b;
    ANY_TYPE c;
} s;

Can I safely assume that the following assumptions will always be true on all platforms?

((char *)&s.a) < ((char *)&s.c)
((char *)&s.a + sizeof(s.a) + sizeof(s.b)) <= ((char *)&s.c)

In C++ too?

like image 301
airman Avatar asked Oct 17 '11 12:10

airman


People also ask

How are structure members stored in memory?

Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.) If necessary, padding is added before each struct member, to ensure correct alignment. Each primitive type T requires an alignment of sizeof(T) bytes.

How much memory does a struct use?

Structure Padding Processor doesn't read 1byte at a time from memory.It reads 1 word at a time. In 32 bit processor, it can access 4 bytes at a time which means word size is 4 bytes. Similarly in a 64 bit processor, it can access 8 bytes at a time which means word size is 8 bytes.

Where is struct stored in memory?

Struct will be always allocated memory in Stack for all value types. Stack is a simple data structure with two operations i.e. Push and Pop . You can push on the end of the stack and pop of the end of stack by holding a pointer to the end of the Stack. All reference types will be stored in heap.

What section of memory will you allocate the struct instances in?

Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member.


1 Answers

Yes, in C at least. The compiler is free to insert padding after any structure member but it must not reorder the members.

It must also not insert padding before the first member.

From C99, 6.7.2.1:

13/ Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

15/ There may be unnamed padding at the end of a structure or union.

like image 93
paxdiablo Avatar answered Oct 12 '22 20:10

paxdiablo