← dev

Memory

Mysteries of Memory Management Revealed

Source

Windows is a demand-paged memory system

Address Space

Range of virtual addresses that the operating system assigns to a process. This is the area of contiguous virtual addresses available for executing instructions and storing data.

The range of virtual addresses in an address space starts at zero and can extend to the highest address permitted by the operating system architecture. Source

32bit x86 Address Space

32bit -> 2^32 -> 4 GB

64bit x86 Address Space

64bit -> 2^64 -> 17,179,869,184 GB

Processors can't handle that yet.

Every address space can be:

Every address space is divided in 3

VMMap

Links


Structure packing

Source

Storage of basic C data type are not stored in arbitary locations in memory. There are alignment constraints. Except char.

These, in vanilla ISAs (Intel, ARM, Risc-V), are referred to as self-aligned.

// on an x64
char *p;   // 64 data bits
char c;    // 8  data bits
           // 24 padding bits -> "slop" not guaranteed to be zeroed
int x;     // 32 data bits

On platforms with self-aligned data types, arrays of basic datatypes do not have padding between elements.

Structs

In general, a struct will be aligned to its widest member. This is the easiest way to make sure all members are self-aligned.

The address of the first member is the address of the struct (Might not be the case in C++)

Stride address. Its the first address following the data structure that has the same alignment as the structure. this becomes trailing padding

If there are nested structs, the inner data will follow the same alignment rules:

struct foo5 {
    char c;                 // 1 byte data
                            // 7 bytes padding
    struct foo5_inner {
        char *p;            // 8 bytes data
        short x;            // 2 bytes data
                            // 6 bytes padding
    } inner;
};

Structure packing

One strategy to make sure your struct is packed, is to order its members by size. It can be descending or ascending order, and the last/first should be the pointer-aligned elements.

Notes: