Pointers & memory
25 steps in 7 sets of C.
The tour C is really about. Pointers first, then generic and function pointers, then malloc and free and the question of who owns what.
There is a set called Ownership and mistakes, and it is there because C gives you no help with either. Structs and strings-in-memory finish it. Twenty-five steps, and this is where C stops being an ordinary language and starts being the one everything else is built on.
Pointers
- PointersAddresses and dereferencing: the heart of C.
- Swap via pointersSwapping two values through pointers, the exercise that explains why C has them.
- Pointer arithmeticWalking an array with pointers instead of indexes.
- Arrays decay to pointersAn array argument is really a pointer, which is why the callee needs a length.
- const on both sidesWhere the const sits decides whether the pointer or the pointee is frozen.
Generic & function pointers
- void pointersA void pointer holds any object address, and the cast back is your responsibility.
- Function pointersA function's name is an address, so it can be stored, passed and called.
- Callbacks with contextThe C convention for a callback: the function pointer plus a void pointer of your own.
- qsort with a comparatorThe standard sort takes element size and a comparison function.
Dynamic memory
- malloc and freeAllocating memory on the heap at run time.
- calloc and zeroingcalloc takes a count and a size, and hands back memory already zeroed.
- reallocResizing a heap allocation, growing an array.
- Growing a bufferDoubling on demand, and never assigning realloc's result over your only pointer.
- memcpy, memmove, memsetThree bulk operations, and the one rule that separates the first two.
Ownership & mistakes
- Who frees it?C has no destructors, so ownership lives in the naming and the comments.
- The classic memory bugsLeak, double free, dangling pointer and off-by-one — shown so you recognize them.
- An arena allocatorOne big block, a bump pointer, and a single free at the end.
- goto for cleanupThe one goto pattern C programmers defend: a single exit that frees what was taken.
Structs
- StructsGrouping related fields into one value type.
- Struct pointersMutating a struct through a pointer with ->.
- typedefGiving types shorter, clearer names.
Strings in memory
- Reverse in placeReverses in place with two indices walking toward each other.
- String library functionsThe <string.h> workhorses for C strings.
Encore
- dynamic_stack.cA growable integer stack backed by malloc and realloc.
- vector.cA growable array as a proper little module: create, push, get, destroy.