OS - Memory

Updated: 2018-12-08

Address Space

  • Virtual address, an abstraction, what does the user program see: [ code | heap ... stack ]

    • code: the program, static
    • stack: function calls, local variables, managed by compiler
    • heap: dynamic memory, created by malloc(), managed by user program
  • under the hood they are spread in physical address by OS

Every address that can be printed out in C is virtual

e.g. in stack:

int x;

a pointer in stack and a int in heap

int *x = (int *) malloc(sizeof(int))

quote:

EVERY ADDRESS YOU SEE IS VIRTUAL Ever write a C program that prints out a pointer? The value you see (some large number, often printed in hexadecimal), is a virtual address. Ever wonder where the code of your program is found? You can print that out too, and yes, if you can print it, it also is a virtual address. In fact, any address you can see as a programmer of a user-level program is a virtual address. It’s only the OS, through its tricky techniques of virtualizing memory, that knows where in the physical memory of the machine these instructions and data values lie. So never forget: if you print out an address in a program, it’s a virtual one, an illusion of how things are laid out in memory; only the OS (and the hardware) knows the real truth. Here’s a little program that prints out the locations of the main() routine (where code lives), the value of a heap-allocated value returned from malloc(), and the location of an integer on the stack:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
    printf("location of code : %p\n", (void *) main);
    printf("location of heap : %p\n", (void *) malloc(1));
    int x = 3;
    printf("location of stack : %p\n", (void *) &x);
    return x;
}

From this, you can see that 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. 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.