Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Programming Shortcut: C

Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about memory, and the data structures built on it.

C does what you say, and nothing more

Every language you have used sits on top of the same thing: a long row of bytes in your computer’s memory. Python, JavaScript, Java and lux all keep that row out of sight. They decide where your values go, how much room each one gets, and when the room can be given back. Most days that’s a gift.

C was made in the early 1970s to write an operating system, and it was made by people who needed to see the row. So C is a thin layer over the machine. It hands you the bytes, tells you where they are, and steps back. It doesn’t check that you stayed inside your array. It doesn’t clean up after you. It does what you say, and nothing more.

That sounds like bad news, and for a big program written in a hurry it can be. For learning, it’s good news. The languages you’ll use after this are built on the things C shows you directly: addresses, blocks of bytes, the stack and the heap. Once you’ve seen them, a lot of behavior that used to feel like magic turns into plain bookkeeping. Why does a list in Python grow without being told to? Why does changing an object inside a function sometimes change it outside, too? Why do some languages need a garbage collector? The answers are all in the row.

This article is about memory: how your data lives in the machine, and the data structures you build out of it. C is the vehicle, and we’ll use only as much of it as the idea needs.

What carries over

You already know most of C’s shape. Its loops, conditionals, functions and structs look like the ones you know, because a great many languages copied them from C. The rows below are the ones that change.

What you knowluxC
a recordstructstruct, laid out field by field in memory
an array[int], knows its lengtha row of values; the length is yours to remember
a growable listqueue += 4doesn’t exist; you build it (the project below)
textstringan array of bytes ending in a zero byte
a value that might be missingOptiona pointer that might be NULL
errors you expectResulta return value you agree to check
memoryhandled for youmalloc to get it, free to give it back

If you learned lux first, here’s the bridge: lux managed memory for you every time you made a struct or added to an array. This article shows what it was doing.

(Option is a way of saying “there may be no value here” that the compiler makes you check; its home in this series is the Rust article. C’s version is a pointer that might be NULL, an address that means “nothing here”, and nothing makes you check it.)

Compile, run, read the warnings

C is compiled: a program called a compiler turns your text file into a program your machine runs directly. The compiler here is GCC, the GNU Compiler Collection. I’ll use Linux, because that’s where GCC is at home. On Debian or Ubuntu, one command installs it:

sudo apt install gcc

Elsewhere, start from GCC’s install page. (A Mac’s own gcc is really a different compiler, Clang, and it takes the same command.)

Make a file called where.c:

#include <stdio.h>

int main(void) {
    int score = 75;
    printf("score is %d\n", score);
    printf("it lives at %p\n", (void *)&score);
    printf("it takes %zu bytes\n", sizeof score);
}

Then compile it and run it:

gcc -std=c23 -Wall -Wextra -Werror -fsanitize=address,undefined -g -o where where.c && ./where

That’s a long command, and every piece of it is there to help you. -std=c23 asks for the current version of the language, C23. -Wall and -Wextra turn on the compiler’s warnings, and -Werror turns every warning into an error, so a warning stops the build instead of scrolling past. -fsanitize=address,undefined builds two sanitizers into your program: extra checking code that watches its memory use and arithmetic while it runs, and stops with a report when something goes wrong. -g keeps your line numbers in the program, so those reports can point at your code. -o where names the result, and ./where runs it.

You’ll see something like this:

score is 75
it lives at 0x7ff3ff500020
it takes 4 bytes

Your address will be different, and it’ll change from run to run. From here on you’ll work the same way: edit, compile with that one command, read what the compiler says, run. Put the command in your shell history and press the up arrow.

Memory is a long row of numbered boxes

Picture your program’s memory as one very long row of boxes. Each box holds one byte, a number from 0 to 255. Each box has a number of its own, counting up from the start of the row. That number is the box’s address.

Every variable you’ve ever made lives in some of those boxes. score in the program above takes 4 of them, starting at the address it printed. Two operators let you ask about this:

sizeof x tells you how many bytes x takes. It comes back as a size_t, the type C uses for sizes, which printf prints with %zu.

&x gives you the address of x: where its first byte lives. printf prints an address with %p, and the (void *) in front says “this is just an address”, which is what %p asks for.

So what does a type mean, down here? A type is two facts: how many boxes, and how to read the numbers in them. An int is four boxes read together as one whole number. You can see the four boxes for yourself by reading the same address as plain bytes:

#include <stdio.h>

int main(void) {
    int n = 258;
    unsigned char *bytes = (unsigned char *)&n;
    for (size_t i = 0; i < sizeof n; i++) {
        printf("box %zu holds %d\n", i, bytes[i]);
    }
}

On a typical laptop that prints 2, 1, 0 and 0. The number 258 is one 256 plus 2, and the machine stores it smallest part first. Nothing about the boxes says “this is an int”. The type lives in your program, and the row just holds numbers.

A pointer is an address you keep

That bytes variable above was a pointer: a variable whose value is an address. You write its type with a star, so int *p is “a pointer to an int”, and you follow it with a star too: *p means “the value at the address in p”.

Here’s why that matters. When you call a function in C, it gets a copy of each argument. A function that tries to swap two numbers it was handed swaps its own copies and changes nothing outside. Hand it the addresses instead, and it can reach back into the caller’s boxes:

#include <stdio.h>

void swap(int *a, int *b) {
    int held = *a;
    *a = *b;
    *b = held;
}

int main(void) {
    int left = 1;
    int right = 2;
    swap(&left, &right);
    printf("left %d, right %d\n", left, right);
}

This prints left 2, right 1. The function received two addresses, copied as usual, and wrote through them.

Now think about a language you know. When a function changes a list you passed it and the change shows up outside, the language passed an address and followed it for you. Whether a variable holds a value or the address of one is called value versus reference semantics, and its home in this series is C#. In C you see the address, because you wrote the &.

An array is a row with no fence

An array is the simplest idea in memory: values of one type, side by side, with no gaps. Print the addresses and you can see it:

#include <stdio.h>

int main(void) {
    int a[4] = {10, 20, 30, 40};
    for (int i = 0; i < 4; i++) {
        printf("a[%d] = %d at %p\n", i, a[i], (void *)&a[i]);
    }
    int *p = a;
    printf("*(p + 2) = %d\n", *(p + 2));
}

The addresses climb by 4 each time, one int apart. And look at the last line. An array’s name works as the address of its first element, and adding 2 to a pointer to an int moves it two ints along, 8 bytes. In fact, a[2] means *(a + 2). Indexing is arithmetic: start at the beginning, step i elements, read what’s there. That’s why reading a[1000] takes the same time as reading a[0], in every language with arrays. The machine doesn’t walk to element 1000; it computes where it is.

Notice what the row doesn’t have: a length. The four boxes of a don’t come with a fifth box saying “4”. The compiler knows the length while a is in sight, but hand the array to a function and the function gets only the address of the first element. Try it:

#include <stdio.h>

void show(int a[4]) {
    printf("inside: %zu bytes\n", sizeof a);
}

int main(void) {
    int a[4] = {10, 20, 30, 40};
    printf("outside: %zu bytes\n", sizeof a);
    show(a);
}

The compiler stops you: 'sizeof' on array function parameter 'a' will return size of 'int *'. Inside show, a is a pointer, 8 bytes on a 64-bit machine, however long the array was. So C functions that take an array nearly always take its length as a second argument. Every language that “knows” its array’s length is keeping that number next to the row for you.

Text is the same story. A C string is an array of bytes with a zero byte at the end to mark where it stops. To find its length, you walk until you hit the zero.

A struct is fields side by side

A struct works like an array whose boxes can be different sizes. Its fields sit in memory in the order you wrote them, one after another. There’s one wrinkle: the machine reads an int fastest when its address is a multiple of 4, so the compiler adds a few unused bytes, called padding, to line things up:

#include <stdio.h>

struct Loose {
    char tag;
    int count;
    char flag;
};

struct Tight {
    int count;
    char tag;
    char flag;
};

int main(void) {
    printf("loose: %zu bytes\n", sizeof(struct Loose));
    printf("tight: %zu bytes\n", sizeof(struct Tight));
}

A char is one byte. Both structs hold one int and two chars, 6 bytes of data, but on a typical machine Loose takes 12 and Tight takes 8. In Loose, three bytes of padding follow tag so that count lines up, and three more follow flag so that the next Loose in an array lines up too. When you have a million of something, the order of its fields starts to matter.

Two places to live

Your program’s memory isn’t one undivided row. Two regions matter for everything you write.

The stack is where a function’s local variables live. When a function is called, it gets a fresh stretch of the stack for its variables; when it returns, that stretch is handed to the next call. It’s fast and automatic, and it has one rule you can’t break: a local variable lives only as long as its function call. So this is a mistake:

#include <stdio.h>

int *make_number(void) {
    int n = 42;
    return &n;
}

int main(void) {
    int *p = make_number();
    printf("%d\n", *p);
}

make_number returns the address of n, but by the time anyone follows that address, n is gone and its boxes belong to someone else. A pointer like that, pointing at memory that’s no longer yours, is called dangling. GCC spots this one and refuses: function returns address of local variable.

The heap is for values that need to outlive the function that made them. You ask for a block of bytes with malloc (“memory allocate”), and it’s yours until you hand it back with free:

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

int *make_number(void) {
    int *n = malloc(sizeof *n);
    if (n == NULL) {
        exit(1);
    }
    *n = 42;
    return n;
}

int main(void) {
    int *p = make_number();
    printf("%d\n", *p);
    free(p);
}

malloc takes a number of bytes and returns the address of a fresh block, or NULL if it couldn’t find one. sizeof *n asks “how big is the thing n points at?”, which keeps the size right if you later change the type. And free(p) gives the block back.

Now the question every language since has had to answer: who calls free? Here it’s main, the last one using the number. In a bigger program, the block might be handed from function to function, stored in a struct, shared by two parts of the program. Exactly one of them must free it, after everyone is done with it. Free it too early and someone is left holding a dangling pointer. Free it twice and you corrupt the heap’s own bookkeeping. Never free it and you have a leak: memory your program holds and can no longer use.

The question “which part of the program is responsible for this block?” is called ownership. C has no answer for it except the one you keep in your head. Other languages picked answers. Java, Python, JavaScript and C# run a garbage collector, a part of the runtime that finds blocks nobody can reach any more and frees them for you. C++ makes ownership a convention: an object frees its memory when it goes out of scope. Rust makes ownership a rule the compiler checks before your program runs.

Rows and chains

Almost every data structure you’ve used is built from two shapes, and you’ve now seen the raw material for both.

The first shape is a row: one block, values side by side, like an array. Finding element i is arithmetic, but the size is fixed when you ask for the block. So how does a list in Python, or an array in lux, grow when you add to it?

It asks for more room than it needs and remembers two numbers: the length, how many values are in use, and the capacity, how many fit. Adding a value usually just fills the next spare box. When the spares run out, it asks for a bigger block, often twice as big, copies everything over, and frees the old one. Copying is slow, but because the block doubles, it happens rarely, and on average each add stays cheap. That’s a growable array, and it’s what you’ll build in the project. Python’s list, Java’s ArrayList, Rust’s Vec and Go’s slices all work this way.

The second shape is a chain: many small blocks, each holding a value and the address of the next. That’s a linked list:

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

typedef struct Node {
    int value;
    struct Node *next;
} Node;

Node *push_front(Node *head, int value) {
    Node *node = malloc(sizeof *node);
    if (node == NULL) {
        exit(1);
    }
    node->value = value;
    node->next = head;
    return node;
}

int main(void) {
    Node *list = NULL;
    for (int i = 1; i <= 3; i++) {
        list = push_front(list, i * 10);
    }
    for (Node *n = list; n != NULL; n = n->next) {
        printf("%d at %p\n", n->value, (void *)n);
    }
    while (list != NULL) {
        Node *next = list->next;
        free(list);
        list = next;
    }
}

Two small new pieces of C here. typedef gives the struct the short name Node. And node->value means “follow the pointer node, then take the field value”; it’s shorthand for (*node).value.

Each node was its own malloc, so the nodes sit wherever the heap had room, not side by side. Adding at the front is cheap: one small block, no copying, however long the list is. Finding the 1000th value is not, because there’s no arithmetic that gets you there. You follow 999 addresses. And look at the cleanup loop at the end. It saves next before freeing the node, because after free(list), reading list->next would be reading memory that’s no longer yours.

Trees are chains that branch. Many hash tables are a row of chains. Once you can see these two shapes, you can guess the costs of most of what a standard library gives you before you read its documentation.

Where C stops looking after you

Most languages you know make a promise: if you read past the end of an array, or use something that’s gone, the program stops with an error. C gives up that promise. When you break one of its memory rules, the result is undefined behavior: the language standard says nothing at all about what happens. Often the program reads whatever bytes happen to be there and carries on, wrong and quiet.

Here’s a use of a freed block, hidden inside a function where the compiler can’t see it:

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

void finish(int *scores) {
    free(scores);
}

int main(void) {
    int *scores = malloc(3 * sizeof *scores);
    if (scores == NULL) {
        return 1;
    }
    scores[0] = 90;
    finish(scores);
    printf("%d\n", scores[0]);
}

Built without the sanitizers, this ran and printed 1584348641 when I tried it. Not 90, not an error, just a number that happened to be in those boxes. Built with the usual command, it stops at once, with a report that starts ERROR: AddressSanitizer: heap-use-after-free and names the line that read the freed block, the line that freed it, and the line that allocated it in the first place. Change i < 4 to i <= 4 in the array example and you’ll get its sibling, stack-buffer-overflow.

That’s why the sanitizers are in the build command from the first program: they put back the checks C took out.

Beware of ignoring warnings. In most languages a warning is advice. In C it’s often the only notice you’ll get that your program has undefined behavior in it, and the program will still compile and may still seem to work, until it doesn’t. Keep -Wall -Wextra -Werror on, always, and when a warning appears, fix the cause. Don’t add a cast or a pragma to make it go quiet: a silenced warning is the same bug, now invisible. Every one you read teaches you a rule of the row you didn’t know yet.

Build a growable array

The project is the row that grows. It’s in projects/c/vec.c. “Vec”, short for vector, is a common name for a growable array. Here’s the heart of it:

typedef struct {
    int *data;
    size_t length;
    size_t capacity;
} Vec;

void vec_push(Vec *v, int value) {
    if (v->length == v->capacity) {
        size_t bigger = v->capacity == 0 ? 4 : v->capacity * 2;
        int *moved = realloc(v->data, bigger * sizeof *moved);
        if (moved == NULL) {
            fprintf(stderr, "out of memory\n");
            exit(1);
        }
        printf("grew %2zu -> %2zu: block at %p is now at %p\n",
               v->capacity, bigger, (void *)v->data, (void *)moved);
        v->data = moved;
        v->capacity = bigger;
    }
    v->data[v->length] = value;
    v->length++;
}

A Vec is three things: the address of a block on the heap, the length, and the capacity. When the block is full, vec_push calls realloc (“reallocate”), which does the grow-and-copy in one step: it finds a block of the new size, copies the old contents in, frees the old block, and returns the new address. Sometimes it can stretch the old block in place, and then the address doesn’t change. Either way, the old address may no longer be valid, which is why v->data is replaced straight away.

The file also has vec_get, which checks the index against the length before reading (the fence that plain C arrays lack), and vec_free, which hands the block back. Its main pushes the squares of 1 to 20 and adds them up. Build and run it from the projects/c folder with the same command you’ve used all along:

gcc -std=c23 -Wall -Wextra -Werror -fsanitize=address,undefined -g -o vec vec.c && ./vec
grew  0 ->  4: block at (nil) is now at 0x502000000010
grew  4 ->  8: block at 0x502000000010 is now at 0x503000000040
grew  8 -> 16: block at 0x503000000040 is now at 0x506000000020
grew 16 -> 32: block at 0x506000000020 is now at 0x50c000000040
20 numbers in room for 32, total 2870
the 10th is 100

(nil) is how printf shows NULL on Linux: the first push starts from no block at all. Twenty pushes, four trips to realloc. Change the 20 in main to 1,000 and it takes only nine. That’s doubling at work.

Look at the addresses, too. With the sanitizer on, every grow moved the block when I ran it: the sanitizer holds freed memory back so that stale pointers are easy to catch. Build without -fsanitize=address,undefined and you’ll probably see some grows stay put. So a pointer into a Vec can survive one push and dangle after the next. The second “Try this next” item at the end of the file walks you into that bug.

What I left out

I skipped the preprocessor (the #include lines and their relatives), header files and programs split across many files, const, unions, function pointers, and nearly all of C’s standard library. I didn’t cover build tools such as make, or the long list of things that count as undefined behavior. None of them change the picture of the row, and each is easy to pick up once you have it.

cppreference’s C reference is the place to look things up: every function, every operator, and which version of C added it. Modern C by Jens Gustedt is a whole book on C as it’s written today, updated for C23, and free to read online. Beej’s Guide to C Programming is friendlier, and also free. And GCC’s page on sanitizers lists the other checkers it can build into your program.

Ask the machine

The manual for every C library function is already on your disk. Run:

man 3 malloc

Bring it one question: what does realloc do if it can’t find a bigger block, and what happens to your old block then? The answer is why the project stores the result in moved before touching v->data.

Then ask the compiler what your code turned into. Put this in third.c:

int third(int *a) {
    return a[2];
}

and run gcc -S -O1 -o - third.c. That prints the machine instructions GCC wrote for you. Somewhere in there is a[2]. Can you find it, and does it look like “start at the address, step two ints along”?

  • C++ takes the ownership question C leaves open and answers it by convention, with objects that free their own memory.
  • Rust answers it with a compiler that checks every rule, and it’s the home of Option.
  • C# teaches value and reference semantics, the copy-or-address question from the swap example.
  • Debugging is about finding out what a running program is actually doing, the next step once a sanitizer has told you where it went wrong.

Tested with GCC 14.2, November 2026.