This is not the current version of the class.

Data representation 3: Layout and allocators

Overview

Last time, we examined the way C++ compilers assign sizes to objects, and the way they lay out compound objects in memory. This time we explore struct alignment in more depth and introduce pointer arithmetic and segments (general areas of memory).

Objects in memory

Alignments and compound types

Struct alignment practice

struct s {
    char a;
    T1 b;
    T2 c;
    T3 d;
};

Struct rule, mathematically

Alignment and malloc

Pointer representation and address representation

Pointer arithmetic

Pointer comparisons

T a[N];
int i = ..., j = ...;
T* p1 = &a[i];
T* p2 = &a[j];

p1 == p2                i == j
p1 != p2                i != j
p1 < p2                 i < j
p1 > p2                 i > j
p1 <= p2                i <= j
p1 >= p2                i >= j

Pointer addition and subtraction

T a[N];
int i = ..., j = ..., k = ...;
T* p1 = &a[i];
T* p2 = &a[j];

p1 + k     ==     &a[i] + k     ==    &a[i + k]
p1 - k     ==     &a[i] - k     ==    &a[i - k]
p1 - p2    ==   &a[i] - &a[j]   ==    i - j        // type of `p1 - p2` is `ptrdiff_t` == `long`

p1 += k    ==    p1 = p1 + k    ==    p1 = &a[i + k]
++p1       ==    p1 = p1 + 1    ==    p1 = &a[i + 1]

Valid indexes

Pointer arithmetic vs. address arithmetic

Union types

int main() {
    union {
        int a;
        int b;
        char c;
        char d;
    } u;
    u.a = 61;
    hexdump_object(u);
}
addressof(u.mI) = addressof(u)
sizeof(u) = maxI sizeof(TI)
alignof(u) = maxI alignof(TI)

Segments

Segment explorer

#include <cstdio>
#include "hexdump.hh"

int i1 = 61;
const int i2 = 62;

int main() {
    int i3 = 63;
    int* i4 = new int{64};

    hexdump_named_object(i1);
    hexdump_named_object(i2);
    hexdump_named_object(i3);
    hexdump_named_object(i4);
    hexdump_named_object(*i4);
}

Segment names

How do segments grow?