typestar

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.

Start this tour

Pointers

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

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

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.

The other C tours