What a C++ Object Looks Like in Memory: From Source Code to Bytes

Why Can the Same Packet Have Different Sizes?

Give the following class, unchanged, to two compilers, and they may produce two different values of sizeof(Packet):

class Packet {
public:
    char kind;

private:
    int payload;

public:
    short flags;
};

With the default options, the two compilers may also happen to produce the same result; the standard guarantees neither that they agree nor that they differ — the size is decided by the implementation and its ABI.

Which compiler is wrong? Very likely, neither. This definition specifies three non-static data members and their types, as well as language properties such as access control. It does not, however, define the object size as the simple sum of the member sizes, much less provide a byte layout that is universal across platforms. To satisfy alignment requirements, an implementation may insert padding between members or at the end of the object; the standard also leaves freedom in the ordering of members in different access-control sections. Consequently, changing the compiler, target platform, or application binary interface (ABI) may change both the size and the member offsets.

The real risk is not a particular number returned by sizeof, but the scope we assign to that number. Treating the result of the current implementation as a rule of the language standard, or treating one memory diagram as a promise made to all C++ programs, extends the conclusion beyond its boundary. So does treating one stable run of a program as proof of legality. The first task in discussing the C++ object model is not to memorize offsets, but to learn how to determine who guarantees a conclusion and under what conditions it holds.

First Determine Who Guarantees a Conclusion, Then Examine How the Machine Implements It

When facing a low-level phenomenon, first classify conclusions into three categories according to the source of their guarantees.

The first category is guarantees from the language standard. For example, sizeof(char) is always 1, and the sizeof of a complete object type is nonzero. A complete object of an empty class must therefore have nonzero size, but the standard does not require it to occupy exactly one byte in every implementation; the common result of 1 is merely an implementation phenomenon. Likewise, array elements are contiguously allocated, and the array stride equals the element size. These conclusions do not depend on any particular debugger output.

The second category is choices and conventions made by implementations and ABIs. Implementation-defined behavior requires the implementation to document the choice it makes; for example, the implementation must specify the extent of its support for extended alignment. Unspecified behavior allows an implementation to choose among the possibilities given by the standard without requiring each choice to become an interface promise on which programs can rely. Many specific details of object layout belong at the implementation level. When separately compiled artifacts must work together, the ABI further specifies binary interfaces such as data layout, calling conventions, and name mangling. It is a contract that coordinates implementations; it does not thereby become part of the C++ standard.

The third category is undefined behavior. Once an operation triggers undefined behavior, the standard imposes no requirements on the program’s behavior. “It runs on my machine,” “the result is stable with optimization disabled,” and “another compiler merely gives a different result” cannot turn it into implementation-defined behavior. Differences in the second category are legal but not necessarily portable; the third category has lost the language’s semantic guarantees altogether. The two must not be conflated.

This yields a fixed order of checks: first confirm that the source is valid and identify the standard’s guarantees; then consult the implementation and ABI conventions; and finally use controlled experiments to observe the current build. This order cannot be reversed. Machine output can explain how an implementation works, but it cannot supply the language prerequisites missing from invalid source code.

Identify the Subject: Objects, Storage, and Bytes Are Not the Same Thing

Many layout disputes arise from confusing their subjects. An object is a language-level entity that occupies storage and has a type, a lifetime, and an address. A variable, by contrast, is introduced by a declaration and has either an object type or a reference type. A variable of object type associates a name with an object, but the two do not correspond one-to-one: a non-static data member is an object but not a variable; a temporary object produced by expression evaluation is not a variable either; and a variable of reference type certainly cannot simply be understood as another independent unit of object storage.

A type describes a category of objects, while storage provides space; these cannot substitute for each other either. Obtaining a region of storage through an allocation operation does not mean that a usable object necessarily already exists within it, nor is having the same address sufficient by itself to establish object identity. When making observations, answer at least these questions separately: Which object is this? What is its type? How was it created? What is its address? What stage of its lifetime is it in?

Storage duration describes how the storage occupied by an object persists. The language rules classify it as static, thread, automatic, or dynamic. Local variables usually have automatic storage duration, and objects created by new have dynamic storage duration. In int* p = new int{0};, however, the pointer variable p itself has automatic storage duration, while the object denoted by *p has dynamic storage duration. How long storage persists and whether an object’s lifetime has begun or ended are two related questions; storage duration cannot be assessed merely by checking whether the storage still exists.

Objects also have internal structure. An object that is not a subobject of any other object is a complete object. A member object within a class object is a member subobject, and the portion of a derived-class object corresponding to a base class is a base class subobject:

struct Base { int b; };
struct Derived : Base { int d; };
Derived obj;

Here, obj is a complete object containing a Base base class subobject and the member subobject d, while b is located within the Base subobject. This distinction directly affects layout analysis. A complete object of an empty class must be nonzero in size, but the ABIs adopted by some implementations allow an empty class used as a base class subobject to reuse the storage of the enclosing object. This is subobject handling under particular layout rules. It neither implies that a complete object can have size zero nor applies directly to ordinary member subobjects. Similarly, the address relationships among a complete object and its subobjects are determined by the particular layout; containment in the language does not promise arbitrary offsets.

At the byte level, object representation and value representation must also be distinguished. For an object of type T, its object representation consists of the N unsigned char or std::byte units occupying that object’s storage, where N corresponds to sizeof(T). Its value representation is the set of bits within that representation that participate in determining the object’s value. The object representation may contain bits that do not contribute to the value, so two objects having equal values does not mean that all their bytes are necessarily identical. +0.0 and -0.0 illustrate why numeric comparison must not be conflated with the underlying representation.

The object representation provides an entry point for observing and copying bytes, but this does not make every byte operation legal. For trivially copyable types, the object representation can be copied as specified to copy the value. Before writing arbitrary bytes into an object representation and then reading the object, however, the constraints imposed by the type and the value representation must first be checked. Writing an object’s bytes verbatim to a file also does not automatically produce a serialization format that works across compilers and platforms.

Follow the Translation Unit from Language Entities to a Process

Classes and objects in source code do not enter a process’s address space directly; they pass through several stages. Typically, one source file, together with the headers and other content included during preprocessing, forms a translation unit. The compiler performs semantic analysis and code generation on it, producing an object file that contains machine code, data, symbols, and relocation information. If a function has only a declaration in the current translation unit, the address corresponding to its definition can be left for the linker to resolve.

Template instantiation also occurs during compilation. A template definition describes rules for generating code. When a template is used with particular template arguments, the implementation performs semantic checks according to the definition and generates the corresponding specialization as needed. This is not a linker subsequently replacing one piece of generic machine code with different types. Multiple translation units may legitimately contain definitions of the same inline function or template instantiation. The one-definition rule (ODR) specifies the conditions for repeated definitions, and common implementations may use mechanisms such as COMDAT to coalesce duplicate entities at link time. Linker deduplication does not permit source code to violate the ODR.

The linker combines object files and libraries, resolves symbol references, and performs relocation to form an executable file or another loadable artifact. Only after the operating system loads it is an executable image formed in the process. Consequently, an unresolved reference in an object file, an address in an executable file, and a machine instruction at run time answer different questions. When interpreting observational evidence, first identify the stage from which it comes, then determine what conclusion it can support.

After loading, the language’s storage durations have typical correspondences with common implementation regions: local objects with automatic storage duration are usually accommodated by stack frames, objects with dynamic storage duration usually use heap storage, and static data is organized into corresponding file representations according to its initialization and mapped into the process. But “automatic objects must be on the stack, and dynamic objects must be on the heap” is not an address guarantee made by the language standard.

On platforms that use ELF, .text, .rodata, .data, and .bss are likewise organizational mechanisms of a particular format and platform, not synonyms for C++ terms.

A local const object can still have automatic storage duration; const by itself does not automatically move it into a read-only region. Page write protection is an operating-system and hardware mechanism and likewise cannot change the language-level legality of modifying an object that was originally const.

The ABI sits on this path of cooperation: the caller and callee must have consistent expectations for argument passing, return values, class layout, and linkage symbols. The Itanium C++ ABI is a convention adopted by GCC, Clang, and others on various Unix-like platforms; MSVC environments use different conventions. No ABI’s provisions thereby become standard requirements for every implementation. Source compatibility does not imply binary compatibility either: even if the header has not changed, an old caller may still have the old size, offsets, and calling assumptions built into it.

The layered conventions among the language standard, the implementation and ABI, and the particular machine environment.

A Four-Step Framework for a Reviewable Layout Observation

The preceding discussion can be summarized in four steps: establish the level of the conclusion, distinguishing language guarantees, implementation conventions, and undefined behavior; identify the object under discussion, specifying whether it is a complete object or a subobject, together with its type, storage, and lifetime; trace the path carrying the entity, confirming whether the evidence comes from compilation, linking, loading, or execution; and only then proceed to a controlled experiment, formulating a hypothesis, cross-checking the evidence, and limiting the scope of the conclusion.

Take Record as an example. First use language facilities to print addresses legitimately, and formulate a hypothesis on that basis:

#include <iostream>
#include <memory>

struct Record {
    char tag;
    int count;
    double ratio;
};

int read_count(const Record& r) { return r.count; }

int main() {
    Record records[2] = {{'A', 7, 0.5}, {'B', 8, 0.25}};
    std::cout << sizeof(Record) << ' ' << alignof(Record) << '\n'
              << sizeof(records) << '\n' << std::hex
              << std::addressof(records[0]) << '\n'
              << std::addressof(records[1]) << '\n'
              << static_cast<void*>(std::addressof(records[0].tag)) << '\n'
              << static_cast<void*>(std::addressof(records[0].count)) << '\n'
              << static_cast<void*>(std::addressof(records[0].ratio)) << '\n'
              << std::dec << read_count(records[0]) << '\n';
}

It can be built with g++ -std=c++17 -O0 -g observe.cpp -o observe. -O0 and -g merely make the code and debugging information easier to observe; they do not imply that an optimized build will retain the same instructions. sizeof queries the storage size required by a type or expression, and alignof queries the alignment requirement. C++ defines a byte through sizeof(char) == 1, and one byte need not be eight bits. These two operators establish a baseline, but they do not directly identify where padding is located.

If sizeof(Record) is greater than the sum of the three member sizes, padding may be suspected, but its location cannot yet be inferred. Combining member addresses with the object’s starting address can estimate the distances between members; comparing these with alignof(Record) then checks the alignment characteristics exhibited by the object address. sizeof(records) == 2 * sizeof(Record) reflects the contiguous arrangement of array elements and their stride. However, the end of the last member is not necessarily the end of the object, because tail padding may also be present. Absolute addresses may be affected by stack location, dynamic loading, and address-space randomization. The relationships among addresses are therefore worth recording; no particular hexadecimal value should be expected to reproduce.

Next, use the debugger and disassembly to cross-check the evidence rather than repeatedly collecting the same numbers:

gdb ./observe
(gdb) break read_count
(gdb) run
(gdb) ptype /o Record
(gdb) p sizeof(Record)
(gdb) p &r
(gdb) p &r.count
(gdb) disassemble /r read_count

In GDB versions that support this command, ptype /o displays member sizes and offsets, which can corroborate the address-based estimates. GDB displays the results of p &r and p &r.count as typed pointers, in a format determined by the debugger. This differs from the source code, which uses static_cast<void*> to pass member addresses uniformly to the output stream. Disassembly is used to examine how the function obtains the address of the object denoted by r, and which base address and displacement it uses when reading count. If these pieces of evidence disagree, first check whether the same source code, the same type definitions, and matching debugging information were used, rather than selecting only the item that matches expectations. When the object representation needs to be inspected, first obtain sizeof(Record) for the current build, then execute x/Nbx &r with that byte count. The padding bytes do not correspond to stable C++ values.

Compiler layout reports are another kind of evidence. GCC’s -fdump-lang-class and Clang’s -Xclang -fdump-record-layouts can output layout information, but their options, formats, and availability vary among toolchains. Optimization may also inline functions, eliminate objects, or keep values in registers. In that case, the observation point must be relocated instead of insisting on finding the stack object from a debug build. Disassembly shows the access pattern under the current target architecture and calling convention; it is not a C++ requirement for a particular instruction or register.

Source output, a debugger, a compiler layout report, and disassembly jointly cross-check the object layout of the current build.

The final experimental record should keep three kinds of statements separate: “array elements are contiguous and have a stride equal to the element size” is a language conclusion; “the member addresses exhibit a particular distance in this build” is an observation; and “padding lies between these two members” is an interpretation that requires joint support from evidence such as addresses and layout reports. A reviewable record should also preserve the question, source code and complete build command, compiler and target environment, direct results, and interpretation. Changing the compiler, platform, or optimization options creates new experimental conditions. Failing to observe a symbol or instruction also does not prove that the corresponding entity or semantics does not exist.

Finally, organize the conclusions that can be retained across environments into a checklist:

  • Check validity before discussing layout; stable execution cannot validate undefined behavior.
  • sizeof(char) == 1, nonzero size for complete objects, and contiguous arrays with element-size strides are language conclusions. The size and offsets of a particular class must be queried from or observed in the current implementation on this platform.
  • An object is not the same as a variable, a type, or storage. When discussing addresses, specify whether the subject is a complete object or a subobject; when discussing bytes, distinguish the object representation from the value representation.
  • Storage duration is not an alias for a stack, a heap, or a file section, and const and platform read-only protection are not rules at the same level.
  • An ABI coordinates binary artifacts only within its scope; no ABI’s layout and calling details are universal language guarantees.
  • Summarize each observation in two sentences: what was seen with the current source code, toolchain, target, and options; and which part can be generalized on the basis of language rules or implementation documentation, together with the scope of that generalization.

The result is not a “standard memory diagram” detached from its conditions, but a method that can be tested again after moving to another environment. With this method, the object model is no longer a set of numbers to memorize. It becomes a complete path from language semantics to machine evidence, and from that evidence back to the boundaries of the conclusions.

Share: