Question

Consider the following C++ class:

class MyClass
{
    TypeA a;
    TypeB b;
    TypeC c;
};

The compiler I use creates representations of this class in a way that the order of the members in memory is the same order I used in the class definition. I recently encountered a program where this fact was exploited to initialize the members. I know this is a very bad idea because the layout depends on the compiler but I didn't write the code and it worked so far.

I was wondering if ASLR features in modern operating systems could mess this up. I'm pretty sure this is not the case if the object is instantiated dynamically on the heap. But what about other cases?

Was it helpful?

Solution

No... the ordering in the memory layout is guaranteed by the Standard, although there can be padding between members too (always included in the sizeof result, but that does mean hacky code like you've described may want to use an explicit pragma to pack data members or use offsetof to calculate the range of offsets to operate on, otherwise they may break on some other compiler / compiler-settings where the layout differs.

Separately, the layout of objects is identical regardless of where those objects are created: globals, stack, heap - it's always the same. Consider - offsetof is a compile time constant.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top