Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For multiple instances of the same object, are member variables stored at the same offset?

Say I have a struct Foo:

struct Foo
{
    char a;
    int b;
} Foo1, Foo2;

The compiler may insert padding so that Foo::a is stored at the start of the object’s memory, and Foo::b is stored at an offset of 0x04 (say on a 32-bit system for example).

If I create multiple instances of this object Foo1 and Foo2, will they always have the same padding? Is there ever a case where Foo1::b is stored at offset 0x04 and Foo2::b is stored at offset 0x08 for example?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For multiple instances of the same object, are member variables stored at the same offset?

Yes.

If I create multiple instances of this object Foo1 and Foo2, will they always have the same padding?

Yes.

Is there ever a case where Foo1::b is stored at offset 0x04 and Foo2::b is stored at offset 0x08 for example?

No.


This assumption holds only within the program. Compile the program on another system, and the offset can be different there.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading