logo

Memory

Virtual vs Physical

Every address that can be printed out in C is virtual, any address you can see as a programmer of a user-level program is a virtual address. The printed out address is an illusion of how things are laid out in memory. Only OS knows the physical memory.

Virtual Address Space

Virtual address is an abstraction of 3 parts:

  • code: the program, static.
  • stack: function calls, local variables, managed by compiler, e.g. int x;.
  • heap: dynamic memory, created by malloc(), managed by user program, e.g. int *x = (int *) malloc(sizeof(int)).
  • under the hood they are spread in physical address by OS.

Order of the 3 parts: code comes first in the address space, then the heap, and the stack is all the way at the other end of this large virtual space.

So it looks like this:

[ code | heap ... stack ]

To prove it:

#include <stdio.h>
#include <stdlib.h>
int main() {
    printf("code(main) : %p\n", (void *) main);
    printf("heap(1) : %p\n", (void *) malloc(1));
    printf("heap(2) : %p\n", (void *) malloc(2));
    int x1 = 1;
    printf("stack(x1) : %p\n", (void *) &x1);
    int x2 = 2;
    printf("stack(x2) : %p\n", (void *) &x2);
    return 0;
}
code(main) : 0x400570
heap(1) : 0xcf6020
heap(2) : 0xcf6040
stack(x1) : 0x7fffdae25218
stack(x2) : 0x7fffdae25214

Again all of these addresses are virtual, and will be translated by the OS and hardware in order to fetch values from their true physical locations.

Slab Allocation

https://en.wikipedia.org/wiki/Slab_allocation

Eliminates fragmentation caused by allocations and deallocations.