Memory: addresses, the stack and the heap

Memory (RAM) is a long row of bytes, each with a number: its address. A program's memory is split into regions:

RegionHoldsLives
text (code)the program's instructionsthe whole run
globalsglobal and static variablesthe whole run
heapblocks from malloc / newuntil free / delete
stacklocal variables and call framesuntil the function returns

Where things live

#include <stdio.h>
#include <stdlib.h>

int counter = 0;   // a global

void inner(void) {
    int deeper = 2;   // a local of a later call: lower on the stack than main's
    counter += deeper;
}

int main(void) {
    int local = 1;
    int *block = malloc(sizeof(int));   // a block on the heap
    *block = 3;
    counter++;
    inner();
    printf("counter = %d, local = %d, *block = %d\n", counter, local, *block);
    free(block);
    return 0;
}
Open in compiler

Step through and read the address under each name in the memory view: the global counter sits low in memory (around 0x100000), the malloc block in the heap (around 0x55a00000), and the locals near the top (0x7fff...), on the stack. The stack grows downwards: inner is called later, so its deeper gets a lower address than main's locals. (Real systems choose the exact addresses at random on each run, a defence called ASLR, but the order is the same on 64-bit Linux.)

The bytes of an int

#include <stdio.h>

int main(void) {
    int x = 0x12345678;
    unsigned char *p = (unsigned char *)&x;
    printf("bytes in memory:");
    for (int i = 0; i < 4; i++) printf(" %02x", p[i]);
    printf("\n");
    printf(p[0] == 0x78 ? "little-endian\n" : "big-endian\n");
    return 0;
}
Open in compiler

An int takes 4 bytes. Reading them one at a time through an unsigned char * shows that the computer stores the lowest byte first: 0x12345678 is stored as 78 56 34 12. This is little-endian order, used by Intel, AMD and most ARM chips. Networks send numbers big-endian (highest byte first), so programs that talk over a network convert.

Quick check

1. Where does a local variable live?
2. Which region keeps a malloc block until free?
3. On a little-endian computer, which byte of 0x11223344 comes first in memory?
My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.