13.6 — Structs and classes in memory

📘 Chapter 13⏱ about 2 min read✍️ Beginner friendly
Read one box at a time. No rush.

Members are just offsets#

A struct's members sit next to each other in memory. Each member is at a fixed distance — an offset — from the start.

struct Player{    int health;   // offset 0    int level;    // offset 4    int score;    // offset 8}; int getScore(const Player& p){    return p.score;} void heal(Player& p){    p.health += 10;}
Assembly (x86-64, GCC -O1)
getScore(Player const&):        mov     eax, DWORD PTR [rdi+8]        retheal(Player&):        add     DWORD PTR [rdi], 10        ret
Key idea

When you see [reg+4], [reg+8], [reg+12]... used again and again, you're probably looking at a struct or class. Reverse engineers rebuild the struct by collecting these offsets.

Virtual functions and the vtable#

A class with virtual functions (11.3 — Inheritance: building on a class) gets a hidden first member: a pointer to a vtable — a table of function addresses.

struct Animal{    virtual ~Animal() = default;    virtual int legs() const { return 4; }}; int countLegs(const Animal& a){    return a.legs();}
Assembly (x86-64, GCC -O1)
countLegs(Animal const&):        sub     rsp, 8        mov     rax, QWORD PTR [rdi]        call    [QWORD PTR [rax+16]]        add     rsp, 8        ret
  1. mov rax, [rdi] loads the hidden vtable pointer from the start of the object.
  2. call [rax+16] calls whatever function is in slot 3 of the table (each slot is 8 bytes; the first two are used by the virtual destructor).

That's how one call can run Cat::legs or Bird::legs: each class has its own vtable.

vtable

A hidden table of function addresses that a class with virtual functions uses to decide, while running, which version of a function to call.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.