C Roadmap

C is a compact systems language that compiles to fast machine code and gives you direct access to memory. Operating systems, embedded firmware, databases, network software and the runtimes of other languages are built with it, and most languages can call C libraries. Typical applications are kernels, drivers, firmware and libraries. Roles in systems, embedded, infrastructure and performance work still ask for it.

This roadmap starts with installing a compiler and ends with threads, tooling and the idioms used in real codebases. The middle of the path is the part interviews care about most: pointers, arrays, strings, the heap, undefined behaviour and how a program is built. Each topic has a short explanation, often with an example, and a practice task. Core topics are expected of every C programmer, recommended topics are common in jobs, and optional ones can wait.

By the end you will be able to write a small, correct, multi-file C program, find memory bugs with proper tools and explain what the machine is doing. Practise in coding practice and track your progress in progress page.

Level
Beginner to advanced
Time
14–20 weeks at about 8 hours a week, less if you already program in another language
Scope
54 topics in 10 stages
Before you start
Basic programming ideas: variables, conditions, loops and functions in any language; Comfort with a terminal: files, directories and running commands; Basic binary and hexadecimal numbers (see Computer Science Roadmap); Helpful but optional: Linux Roadmap basics and Git and GitHub Roadmap

What you will be able to do

  • Build and run multi-file C programs with a build system and sensible warnings.
  • Explain how pointers, arrays and strings are laid out in memory and use them safely.
  • Manage heap memory with clear ownership, without leaks or double frees.
  • Recognise undefined behaviour and use sanitizers and a debugger to find it.
  • Implement common data structures such as dynamic arrays, linked lists and hash maps.
  • Read and write files with proper error handling.
  • Write simple multi-threaded programs that avoid data races.

The roadmap at a glance

  1. Stage 1Getting Started with CBeginner · 1 week · 7 topics
  2. Stage 2Core Language: Types, Operators and Input/OutputBeginner · 2 weeks · 6 topics
  3. Stage 3Control Flow and FunctionsBeginner · 2 weeks · 8 topics
  4. Stage 4Pointers, Arrays and StringsIntermediate · 3 weeks · 7 topics
  5. Stage 5Dynamic Memory and Undefined BehaviourIntermediate · 2–3 weeks · 5 topics
  6. Stage 6User-Defined Types and Data StructuresIntermediate · 3 weeks · 6 topics
  7. Stage 7Preprocessor, Headers and Build SystemsIntermediate · 2 weeks · 5 topics
  8. Stage 8Standard Library, Errors and FilesIntermediate · 2 weeks · 4 topics
  9. Stage 9Debugging, Testing and ToolingIntermediate · 2 weeks · 3 topics
  10. Stage 10Systems Programming and IdiomsAdvanced · 3 weeks · 3 topics

Stage 1 Getting Started with C

Beginner1 week7 topics

Goal. Install a compiler, build and run a program, and explain what each step from source file to executable does.

Introduction to C Core

C is a small, compiled language that sits close to the hardware. It gives you direct control over memory and very little else: no classes, no garbage collector, no built-in string or list types. Operating system kernels, device drivers, databases, language runtimes and firmware are still written in it, and most other languages can call C code.

Learning C teaches what other languages hide. You see how arrays are laid out, what a string really is, where variables live and what happens when you make a mistake. Interviewers for systems, embedded and infrastructure roles use C questions to test that understanding. See Computer Science Roadmap for the wider foundations.

Practice. Write down five things a language like Python does for you that C leaves to the programmer.

Why Use C, and C vs Assembly vs C++ Core

C trades convenience for predictability. You can tell roughly what machine code a line produces, you control memory layout, and a program has almost no runtime overhead. That matters for kernels, embedded devices with kilobytes of memory, and libraries that must be called from many languages.

Compared with assembly, C is portable across processor families and far easier to maintain, while still letting you drop to inline assembly when needed. On C vs C++, C is smaller and simpler, has no exceptions or templates, and a different object model. C++ is not a strict superset: valid C can be invalid C++, for example by converting a void * to another pointer type without a cast. See Modern C++ Roadmap for the larger language.

Practice. Compile a tiny function with optimisation on, view the assembly with the compiler option that emits it, and match three lines to your C.

C Standards: C89 / C90, C99, C11, C17 and C23 Core

C is defined by ISO standards. C89 (also called C90) is the first. C99 added // comments, declarations anywhere in a block, long long, stdint.h, stdbool.h, designated initialisers, compound literals, inline and variable length arrays.

C11 added _Atomic, _Generic, _Static_assert, anonymous structs and unions, and an optional threads library. C17 is a bug-fix release with no new features. C23 brings bool, true and false as keywords, nullptr, constexpr for objects, typeof, binary literals, digit separators, attribute syntax and #embed.

Choose a standard with a compiler flag such as -std=c11. New projects usually pick C11 or C17 for portability, and C23 where the toolchain supports it.

Practice. Compile the same file with -std=c89 -pedantic and -std=c17 -pedantic, and note which constructs the older mode rejects.

Setting up: Installing C, Compilers and GCC / Clang Core

You need a compiler and a terminal. On Linux, install your distribution's build tools package. On macOS, run the command line tools installer, which provides Clang. On Windows, use WSL for a Linux environment, or MinGW or MSVC for native builds.

GCC and Clang are the two mainstream compilers and share most flags. A good starting set is:

cc -std=c17 -Wall -Wextra -Wpedantic -g main.c -o main

-Wall -Wextra turn on useful warnings, and -g adds debug information. Treat warnings as bugs. TinyCC is a very small, very fast compiler that can even run C files like scripts, handy for quick experiments but not for optimised builds. Other compilers exist for specific chips, such as vendor compilers for microcontrollers.

Practice. Install a compiler, then check its version and the default language standard it uses.

Code Editors, IDEs, VSCode and vim / nvim Recommended

Any text editor works for C. What matters is a language server for completion and diagnostics (clangd is the usual choice), a way to jump to definitions, and a terminal next to your code.

VSCode with a C and C++ extension or clangd is a common, gentle choice. vim and nvim are fast in a terminal, especially over SSH, and plug into clangd too. Full IDEs such as CLion or Eclipse CDT give integrated debugging and project views.

Whatever you pick, generate a compile_commands.json file from your build system so the language server knows your include paths and flags. Learn to build and run from the command line first, so you are not dependent on a tool's hidden settings.

Practice. Configure your editor with clangd and confirm that go-to-definition works on a standard library function.

Running your First Program and the main Function Core

Every hosted C program starts at main. It returns an int status to the operating system, where 0 means success.

#include <stdio.h>

int main(void) {
    puts("Hello, C");
    return 0;
}

#include pastes in a header that declares puts. The two accepted forms of main are int main(void) and int main(int argc, char *argv[]). Writing (void) says there are no parameters; empty parentheses in older C mean unspecified arguments, which is weaker. Reaching the closing brace of main returns 0 automatically from C99 on.

Build with cc hello.c -o hello and run ./hello. Check the status with echo $? in a shell.

Practice. Change main to return 3 and read the exit status from your shell.

Build and Compilation Pipeline Core

Building a C program has four stages. The preprocessor expands includes and macros. The compiler turns each translation unit (one source file after preprocessing) into assembly. The assembler produces an object file. The linker joins object files and libraries into an executable, resolving symbols between them.

You can stop at each stage: -E stops after preprocessing, -S emits assembly, -c produces an object file. Compile errors come from the first stages; "undefined reference" errors come from the linker and mean a declaration was found but no definition was linked.

Each source file is compiled on its own. This is why headers exist: they let one file know the shape of functions defined in another. Understanding this pipeline explains most beginner build errors.

Practice. Split a program into two source files, compile each with -c, then link them by hand and cause an undefined reference on purpose.

Stage 2 Core Language: Types, Operators and Input/Output

Beginner2 weeks6 topics

Goal. Write small programs that declare variables, convert between types, use every operator family and read and print data correctly.

Variables and Initialization Core

A variable is a named piece of storage with a type. You declare it with the type first.

int count = 0;
double ratio = 0.5;
const int limit = 100;

Local variables are not initialised for you. Reading one before assignment gives an indeterminate value, which is undefined behaviour in many cases. Global and static variables are zero-initialised by default.

Initialisation and assignment are different things. Arrays and structs can be initialised with braces, and C99 added designated initialisers such as { .x = 1, .y = 2 } and [3] = 7. An empty brace pair {0} is the classic way to zero a whole aggregate; C23 also allows {}.

Make a habit of declaring variables at the point of first use and initialising them there.

Practice. Declare locals without initialising them, print them with warnings on, and read what the compiler tells you.

Data Types: integers, char, float, double and booleans Core

The basic types are char, short, int, long and long long (each with signed and unsigned forms), float, double and long double. The sizes are not fixed by the language, only minimum ranges. An int is usually 32 bits today, but you should not assume it.

char is a small integer type that holds a character code; whether plain char is signed is implementation-defined. Integer overflow on signed types is undefined behaviour; unsigned types wrap around.

float and double follow IEEE 754 on nearly all platforms, so use double by default and never compare results with == after arithmetic.

There was no boolean type in C89. Since C99, _Bool and the bool macro in stdbool.h exist; in C23 bool is a keyword. Any non-zero value counts as true in a condition.

Practice. Print sizeof for every basic type on your machine and add 0.1 + 0.2 == 0.3 to a test to see the result.

Fixed-width integers and Extended Types Core

When size matters, such as in file formats, network protocols and hardware registers, use the types from stdint.h: int32_t, uint8_t, uint64_t and so on. There are also "least" and "fast" variants and intptr_t for integers that hold a pointer. Use size_t for object sizes and array indexes, and ptrdiff_t for pointer differences. Print them with the macros in inttypes.h, or %zu for size_t.

Extended types cover less common numeric and wide forms: long double, complex numbers in complex.h, wide characters in wchar_t, and in C23 _BitInt(N) for integers of an exact bit width and optional decimal floating types. They are specialised; know they exist and check support before using them.

Practice. Write a function that reads a 32-bit big-endian integer from a byte buffer using uint8_t and shifts.

Type Conversion Core

C converts between types automatically in expressions. Integer promotion widens anything smaller than int to int before arithmetic. The usual arithmetic conversions then bring both operands to a common type.

Surprises come from mixing signed and unsigned. In -1 < 1u the -1 becomes a huge unsigned value, so the comparison is false. Converting a floating value to an integer truncates toward zero, and is undefined if the value does not fit.

Explicit casts such as (double)total / count state your intent. Avoid casts that silence warnings without thinking: a cast between pointer types or one that discards const hides real problems. Compile with -Wconversion and -Wsign-compare to find the risky spots.

Practice. Predict, then run, the result of comparing -1 with 1u and of dividing two ints before and after casting one to double.

Operators: Arithmetic, Comparison, Logical, Bitwise and Ternary Core

Arithmetic operators are + - * / %. Integer division truncates toward zero and % follows it, so -7 / 2 is -3. Division by zero is undefined for integers.

Comparison operators give 1 or 0. Logical && and || short-circuit: the right side runs only if needed. This makes p && p->value safe.

Bitwise operators work on the bits: & | ^ ~ << >>. Use them for flags and masks:

flags |= FLAG_READ;     /* set */
flags &= ~FLAG_WRITE;   /* clear */
if (flags & FLAG_READ) { /* test */ }

Shifting by a negative amount or by the type's width or more is undefined, and right-shifting a negative signed value is implementation-defined. Use unsigned types for bit work.

The ternary cond ? a : b chooses between two expressions. Precedence rules are subtle (== binds tighter than &), so add parentheses.

Practice. Implement set, clear, toggle and test helpers for a 32-bit flags word, and count set bits in a loop.

Input / Output and Printing Variables Core

The standard streams are stdin, stdout and stderr. printf writes formatted output; the format specifier must match the argument type or the behaviour is undefined: %d for int, %u unsigned, %ld, %lld, %zu for size_t, %f for double, %c, %s and %p for pointers.

For input, scanf is risky because a bad format leaves input unread and %s has no limit. Prefer reading a line with fgets into a buffer of known size and then parsing it with strtol or strtod, which report errors.

char line[64];
if (fgets(line, sizeof line, stdin)) {
    long n = strtol(line, NULL, 10);
    printf("%ld\n", n * 2);
}

Write diagnostics to stderr so they do not mix with program output when stdout is piped.

Practice. Write a program that reads numbers line by line until end of input and prints their sum, rejecting lines that are not numbers.

Stage 3 Control Flow and Functions

Beginner2 weeks8 topics

Goal. Structure programs with branches, loops and functions, and control the scope, lifetime and linkage of names.

Control Flow: if / else, switch and the conditional chain Core

if and else choose between blocks based on whether an expression is non-zero. Always use braces, even for one statement. The "goto fail" security bug in a widely used library came from a dangling unbraced line.

switch selects among integer constants. Each case falls through to the next unless you end it with break, which is both a feature and a classic bug. Mark deliberate fall-through with a comment or the C23 attribute [[fallthrough]], and always include a default.

switch (code) {
case 200: puts("ok"); break;
case 404: puts("missing"); break;
default:  puts("other");
}

Put the common or error case first and return early to keep nesting shallow.

Practice. Write a function that classifies an HTTP status code with switch, then compile with -Wimplicit-fallthrough.

Loops: for / while / do while loops, break / continue Core

for (init; test; step) is best when you know the count. while tests first, and do ... while runs the body once before testing, which suits "read, then check" patterns.

break leaves the nearest loop or switch. continue skips to the next iteration. C has no labelled loops, so leaving two nested loops needs a flag, a helper function that returns, or a disciplined goto to a cleanup label.

Beware off-by-one errors and unsigned counters: for (size_t i = n - 1; i >= 0; i--) never ends because an unsigned value is always at least zero. Declare the loop variable inside the for (allowed since C99) so it does not leak into the surrounding scope.

Practice. Print a multiplication table, then rewrite a nested search loop to exit early using a function return.

Functions and Declaration vs Definition Core

Basic functions have a return type, a name, parameters and a body. C passes everything by value: the function receives copies of its arguments. To let a function change a caller's variable, pass its address.

A declaration (prototype) tells the compiler a function's signature: int add(int a, int b);. A definition provides the body and creates the code. A function may be declared many times but defined once across the whole program. Prototypes go in headers so every file sees the same signature.

Arrays do not pass by value; an array parameter is really a pointer, so pass the length too. Return values can be a status code with results written through pointer parameters. Mark helpers used by one file as static to keep them private.

Practice. Write swap(int *a, int *b) and a function returning a status code with its result through a pointer.

Recursive Functions Core

A recursive function calls itself on a smaller problem, with a base case that stops it. Factorial, tree traversal, divide and conquer and parsing nested structures fit naturally.

unsigned long fact(unsigned n) {
    return n <= 1 ? 1 : n * fact(n - 1);
}

Each call uses stack space for its frame. Deep recursion can overflow the stack, which crashes the program; the default stack is usually a few megabytes. The standard does not guarantee tail call optimisation, although optimising compilers often perform it. If depth depends on user input, use an explicit stack or a loop instead. See Data Structures and Algorithms Roadmap for the algorithms that rely on recursion.

Practice. Write recursive and iterative versions of list reversal and compare their stack depth on a very long list.

Variable Scopes, Storage Duration and static Core

Scope is where a name is visible: block scope (inside braces), function parameter scope, and file scope (outside any function). Storage duration is how long the object lives: automatic (until the block ends), static (the whole run) and allocated (until freed).

static has two meanings. Inside a function, it makes a local variable keep its value between calls, living for the whole program. At file scope, it gives a name internal linkage, so no other file can see it. A static local is initialised once, but beware that it makes a function non-reentrant and not thread-safe.

An inner name can shadow an outer one; compile with -Wshadow to catch accidents. File Scope & Storage Duration decisions matter in large programs: keep globals few and private.

Practice. Write a counter function with a static local, then make it thread-safe by passing state in a struct instead.

Linkage and extern Core

Linkage decides whether the same name in different files refers to the same object. External linkage (the default for functions and file-scope variables) lets other files use the name. Internal linkage (static) keeps it private to one translation unit. No linkage applies to locals.

extern declares a variable defined elsewhere: extern int debug_level; in a header, with the single definition int debug_level; in one .c file. Defining a variable in a header that many files include causes duplicate symbol errors at link time.

Use static by default for anything that is not part of a module's public interface, and prefix public names with a module name to avoid clashes, since C has no namespaces.

Practice. Share a global between two files with extern, then break it deliberately by defining it in the header and read the linker error.

Variadic Functions Recommended

Variadic functions take a variable number of arguments, like printf. Declare them with ... and use the macros in stdarg.h.

#include <stdarg.h>
int sum(int n, ...) {
    va_list ap; va_start(ap, n);
    int s = 0;
    for (int i = 0; i < n; i++) s += va_arg(ap, int);
    va_end(ap);
    return s;
}

There is no type checking on the extra arguments, and the function has to know how many there are and their types. Passing the wrong type is undefined behaviour. Small types are promoted: a float arrives as double. To forward arguments, use the v-versions such as vsnprintf. GCC and Clang provide a format attribute so your own printf-like functions get the same warnings.

Practice. Write a log function that takes a format string and forwards to vsnprintf, then add the format attribute.

Command-Line Arguments and Exit Codes Core

argc is the count and argv the array of strings, with argv[0] the program name and argv[argc] a null pointer. All arguments are text; convert numbers with strtol and check for errors.

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "usage: %s FILE\n", argv[0]);
        return 2;
    }
    return 0;
}

Return EXIT_SUCCESS or EXIT_FAILURE from stdlib.h, or small numbers with documented meanings. Shells and scripts rely on exit codes, so a command-line tool that fails must not return 0. exit() runs atexit handlers and flushes streams; _Exit and abort do not. For options like -v and --output, POSIX provides getopt.

Practice. Write a tool that takes a file name and an optional -n flag with getopt and returns distinct exit codes for each failure.

Stage 4 Pointers, Arrays and Strings

Intermediate3 weeks7 topics

Goal. Use pointers, arrays and strings confidently, and explain what each expression refers to in memory.

Pointer Basics and Syntax Core

A pointer is a variable that holds the address of another object. &x gives the address of x, and *p follows a pointer to the object it points at.

int x = 5;
int *p = &x;
*p = 9;        /* x is now 9 */

A pointer has a type so the compiler knows how big the target is and how to read it. Pointers let functions modify the caller's data, let you build linked structures and let you work with memory you allocate yourself. Read declarations from the name outwards: int *a[3] is an array of three pointers to int, while int (*b)[3] is a pointer to an array of three ints.

Print addresses with %p after casting to void *. Always initialise pointers, either to a valid address or to NULL.

Practice. Draw boxes and arrows for a program with an int, a pointer to it and a pointer to that pointer, then print each value.

Pointers & Memory: Pointer Arithmetic Core

Adding 1 to a pointer moves it by the size of its target type, not by one byte. If p is an int *, then p + 1 points to the next int. Subtracting two pointers into the same array gives the number of elements between them as a ptrdiff_t.

int a[4] = {10, 20, 30, 40};
int *p = a;
printf("%d %d\n", *(p + 2), p[2]);   /* 30 30 */

The subscript a[i] is defined as *(a + i). Arithmetic is only valid within an array or one past its end; going beyond that, or comparing pointers to different objects, is undefined behaviour. For raw bytes, cast to unsigned char *. Never do arithmetic on void * in portable code, even though some compilers allow it as an extension.

Practice. Write strlen and a function that reverses an int array in place using only pointer arithmetic.

Arrays Core

An array is a fixed number of elements of one type stored side by side. Its size is part of its type, and sizeof a / sizeof a[0] gives the element count, but only where a is still an array.

In most expressions an array decays to a pointer to its first element. That is why a function parameter int a[] is really int *a and sizeof inside the function gives the pointer size. Always pass the length separately.

There is no bounds checking. Reading or writing past the end is undefined behaviour and the source of many security flaws. C99 variable length arrays let you size an array at run time on the stack; they were made optional in C11 and are best avoided because a large size overflows the stack. Multidimensional arrays are stored row by row.

Practice. Write a function that finds the maximum of an int array of any length and test it with a one-element array.

Strings and Text Processing Core

C has no string type. A string is an array of char ending in a zero byte ('\0'). A literal such as "hi" has type char[3] and lives in read-only memory, so assign it to const char * and never modify it.

The string.h functions assume the terminator: strlen, strcmp, strchr, strstr, strncmp, memcpy, memmove, memset. strcpy and strcat do no length check; prefer snprintf or a bounded copy you write yourself, and always check for truncation. strncpy does not always terminate the result, so it is easy to misuse. Use strtok_r (POSIX) rather than strtok for splitting, as the latter keeps hidden state.

char buf[16];
int n = snprintf(buf, sizeof buf, "%s-%d", name, id);
if (n < 0 || (size_t)n >= sizeof buf) { /* truncated */ }

ctype.h classifies characters. Text is bytes here: UTF-8 works for storage, but strlen counts bytes, not characters.

Practice. Write a function that splits a comma-separated line into fields without modifying the input and check it against a line with empty fields.

void Pointers, Null Pointers and Opaque Pointers Core

A void * can hold the address of any object but cannot be dereferenced or used in arithmetic until cast. It is how C writes generic code: malloc returns one, qsort and bsearch take callbacks over void * elements, and memcpy copies untyped bytes. In C, conversion to and from void * is implicit.

A null pointer points to nothing. Use NULL (or nullptr in C23) and check pointers that may be absent before use. Dereferencing a null pointer is undefined behaviour, though it usually crashes at once.

An opaque pointer hides a structure's layout. The header declares typedef struct stack stack; and function prototypes, while the struct body lives only in the .c file. Callers can pass the pointer around but cannot touch the fields, so you can change the internals without breaking them. This is C's standard way to build encapsulated modules.

Practice. Write an opaque counter module with create, increment, get and destroy functions, and a main that cannot see the struct.

const, Type Qualifiers, volatile and restrict Core

const says an object should not be modified through this name. Position matters: const int *p is a pointer to a constant int (the pointee is read-only), int *const p is a constant pointer (it cannot be repointed) and const int *const p is both. Declare read-only parameters as const so callers and the compiler know.

volatile tells the compiler that a value can change outside the program's control, such as a memory-mapped hardware register or a flag set in a signal handler, so each access must really happen. It does not make operations atomic and is not a threading tool; use _Atomic or a mutex for that.

restrict is a promise that, during the pointer's lifetime, the object it points to is accessed only through that pointer, which lets the compiler optimise. memcpy uses it, and that is why overlapping copies need memmove. Breaking the promise is undefined behaviour.

Practice. Write a function with const and restrict parameters, then try to modify a const pointee and read the error.

Function Pointers and Callbacks Core

A function pointer holds the address of a function. The declaration syntax looks awkward, so use a typedef.

typedef int (*cmp_fn)(const void *, const void *);

static int by_int(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);
}
/* qsort(arr, n, sizeof arr[0], by_int); */

Callbacks let a library call your code: qsort, signal handlers, event loops, plug-in tables. Add a void *user_data parameter so a callback can carry context without globals. Arrays of function pointers make jump tables and state machines. Avoid subtracting integers in a comparison; it overflows, as the example shows with the safe comparison form.

Practice. Build a small command dispatcher that maps names to function pointers in a table and runs the matching one.

Stage 5 Dynamic Memory and Undefined Behaviour

Intermediate2–3 weeks5 topics

Goal. Manage heap memory without leaks or corruption and recognise the common ways C programs go wrong.

Stack vs Heap and the Memory Model Core

A running program has several memory regions. The stack holds local variables and call frames, is managed automatically and is fast, but is small. The heap holds memory you request at run time with malloc and release with free; it is larger and you manage it. Static data holds globals and string literals, and the code segment holds instructions.

The C memory model also defines what the language promises about objects: every object has a type, a size, alignment and a lifetime, and you may access it only through compatible types (the strict aliasing rule). Casting a float * to an int * and reading through it is undefined behaviour; use memcpy to reinterpret bytes safely.

Returning the address of a local variable is a bug, because its frame is gone when the function returns. Data that must outlive a call goes on the heap or in static storage.

Practice. Print addresses of a local, a global, a literal and a malloc block to see the regions, then write a function that wrongly returns a local address.

Dynamic Memory Allocation: malloc, calloc, realloc and free Core

malloc(n) returns a block of n uninitialised bytes, or NULL on failure. calloc(count, size) zeroes the block and checks the multiplication for overflow. realloc(p, n) resizes a block, possibly moving it. free(p) releases it; free(NULL) is safe.

int *a = malloc(n * sizeof *a);
if (a == NULL) return -1;
/* use a */
int *b = realloc(a, 2 * n * sizeof *a);
if (b == NULL) { free(a); return -1; }
a = b;

Use sizeof *a rather than a type name so the code stays correct if the type changes. Never write a = realloc(a, ...) directly: on failure you lose the original pointer and leak it. Every successful allocation needs exactly one free. Do not read freed memory or free the same block twice. Allocation can fail, especially on small systems, so check it.

Practice. Write a function that reads lines of any length from a file, growing its buffer with realloc, and test it with a very long line.

Memory Leakage, Dangling Pointers and Lifetime of Objects Core

A leak happens when you lose the last pointer to a heap block without freeing it. One small leak is harmless; a leak in a loop in a long-running server eventually exhausts memory.

A dangling pointer refers to an object whose lifetime has ended: freed heap memory, or a local variable after its function returned. Using it is undefined behaviour and can appear to work until it does not. Setting a pointer to NULL after free turns later misuse into a clean crash and makes double free harmless in that variable, though other copies of the pointer remain dangling.

Reason about ownership. Decide, for every allocation, which function or structure is responsible for freeing it, and document it in the function's comment. Functions that return a new object say so ("caller frees"). Consistent ownership rules prevent most leaks and double frees.

Practice. Write a leaky function, find the leak with a memory checker, fix it and note the ownership rule in a comment.

Buffer Overflow and Undefined Behavior Core

A buffer overflow writes or reads beyond an array's end. On the stack it can overwrite a return address and let an attacker run code; it is one of the oldest and most costly classes of vulnerability. Classic causes: gets (removed from the language in C11), unbounded strcpy, sprintf and scanf("%s"), wrong size arithmetic, and off-by-one loops.

Undefined behaviour means the standard places no requirement on what happens. The program may crash, give a wrong answer or seem fine, and an optimiser may assume it never occurs and remove your checks. Examples: signed overflow, out-of-bounds access, null dereference, use after free, unsequenced modification such as i = i++ + 1, and reading uninitialised data.

Defences are layered: bounded functions, checked lengths, compiler warnings, sanitizers, fuzzing, and hardening flags such as stack protectors. Unspecified and implementation-defined behaviour also exist, and differ from undefined behaviour in that the program remains valid.

Practice. Write a deliberately unsafe copy function, trigger an overflow, then fix it and catch the original with a sanitizer.

Dynamic Arrays Core

A dynamic array grows as items are added. Keep a pointer, a length and a capacity in a struct. When the length reaches the capacity, double the capacity with realloc. Doubling gives amortised constant-time appends.

typedef struct { int *data; size_t len, cap; } vec;

int vec_push(vec *v, int x) {
    if (v->len == v->cap) {
        size_t nc = v->cap ? v->cap * 2 : 4;
        int *p = realloc(v->data, nc * sizeof *p);
        if (!p) return -1;
        v->data = p; v->cap = nc;
    }
    v->data[v->len++] = x;
    return 0;
}

Remember that realloc can move the block, so pointers into the array become invalid after growth. Use indexes instead of stored pointers. Check for overflow when computing the new size on large inputs.

Practice. Add pop, get and free functions to this vector and run it with 100,000 pushes under a memory checker.

Stage 6 User-Defined Types and Data Structures

Intermediate3 weeks6 topics

Goal. Model data with structs, unions and enums, and implement the common data structures yourself.

Structs and User-Defined Types Core

A struct groups related fields under one name.

struct point { double x, y; };
struct point p = { .x = 1.5, .y = 2.0 };
double d = p.x * p.x + p.y * p.y;

Use . on a struct and -> on a pointer to one (ptr->x means (*ptr).x). Structs are passed and assigned by value, which copies every field including embedded arrays; pass a pointer for large ones. The compiler may add padding between fields for alignment, so field order changes sizeof; order fields largest first to reduce waste. offsetof from stddef.h gives a field's offset.

A struct with a flexible array member (int items[]; as the last field) lets you allocate the header and variable-size data in one block. Bit-fields pack small integers but their layout is implementation-defined, so avoid them for file or wire formats.

Practice. Define a struct for a student record, print sizeof and each field offset, then reorder fields to shrink it.

Unions and Enums Core

A union stores one of several members in the same memory; its size is that of the largest member. Use it with a tag field to make a variant type:

enum kind { K_INT, K_STR };
struct value {
    enum kind kind;
    union { int i; const char *s; } u;
};

Reading a member other than the last one written is allowed for reinterpreting bytes in C (unlike C++), though the result may be a trap representation or implementation-defined. Do not rely on it for portability or byte order.

An enum names a set of integer constants. Constants are plain int values in C and live in the surrounding scope, so prefix them (COLOR_RED). Enums are not type safe: any integer converts to them. C23 lets you pick the underlying type. Use enums for states, error codes and tags, and a switch with -Wswitch warns about missed cases.

Practice. Implement a small value type that holds an int, a double or a string and prints itself by switching on its tag.

Typedef Core

typedef creates a new name for an existing type. It does not make a new type, only an alias. It shortens function pointer types, hides platform-specific types behind one name, and lets a struct be used without the struct keyword.

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

typedef unsigned char byte;
typedef int (*handler)(int);

Do not typedef a pointer to hide the * in ordinary code, because readers then cannot tell the value is a pointer or whether const applies to the pointee. Opaque handle types are the usual exception. POSIX reserves the _t suffix for its own type names, so avoid it in your own libraries if portability matters.

Practice. Rewrite a program that uses long function pointer declarations to use typedefs, and compare the two for readability.

Linked Lists Core

A singly linked list is a chain of nodes, each holding a value and a pointer to the next. Insertion and removal at a known position are constant time; finding an element is linear and cache behaviour is poor compared with arrays.

node *push(node *head, int v) {
    node *n = malloc(sizeof *n);
    if (!n) return head;
    n->value = v; n->next = head;
    return n;
}

Common interview tasks: reverse a list, detect a cycle with two pointers moving at different speeds, find the middle, merge two sorted lists and remove a node by value. A pointer to a pointer (node **) avoids special-casing the head when removing. Doubly linked lists add a prev pointer for O(1) removal given a node. Free every node when finished. See Data Structures and Algorithms Roadmap for more list problems.

Practice. Implement reverse, cycle detection and remove-by-value, and check them with a memory checker for leaks.

Hash Maps and Symbol Tables Recommended

C has no built-in map, so you write or borrow one. A hash map turns a key into an array index using a hash function. Collisions are handled by chaining (each bucket is a linked list) or open addressing (probe for the next free slot). When the load factor grows, allocate a bigger table and re-insert every entry.

Choose a decent string hash, such as FNV-1a or a modern fast hash, and never use a simple sum of characters. Keys that are strings must be copied or have a clear owner, or the table will point at freed memory.

A symbol table is a map from names to information, as used by compilers, interpreters and assemblers. A hash map with scope chains is the typical design: each scope has its own table and lookups walk outwards. Existing C libraries provide ready-made maps if you do not need to write your own.

Practice. Implement a string-to-int hash map with chaining and resizing, then use it to count words in a text file.

Ring Buffers, FIFO Queues and Common Data Structures Recommended

A ring buffer (circular buffer) stores a fixed number of items in an array with a head and a tail index that wrap around using modulo or a bit mask when the capacity is a power of two. It gives O(1) push and pop with no allocation, so it is the standard choice for byte streams, logging, audio and interrupt-to-main communication on embedded systems.

bool rb_push(rb *r, uint8_t b) {
    size_t next = (r->head + 1) & (RB_SIZE - 1);
    if (next == r->tail) return false;   /* full */
    r->buf[r->head] = b; r->head = next;
    return true;
}

Keep one slot empty, or keep a count, to tell full from empty. With one producer and one consumer, careful use of atomics makes it lock-free.

Other common structures to be able to write: stacks, queues, binary trees, heaps and tries. Each is built from arrays, structs and pointers.

Practice. Implement a ring buffer with push, pop and a unit test that fills it, drains it and wraps around twice.

Stage 7 Preprocessor, Headers and Build Systems

Intermediate2 weeks5 topics

Goal. Organise a multi-file project, use the preprocessor safely and automate builds with a build system.

Preprocessors, Header Files and Include Guards Core

The preprocessor runs before compilation and works on text. #include copies a file in; <name.h> searches system paths, "name.h" searches your project first.

A header file holds declarations that several source files share: function prototypes, type definitions, extern variables and macros. It should not contain definitions of functions or variables. Every header needs an include guard so including it twice is harmless:

#ifndef STACK_H
#define STACK_H
/* declarations */
#endif

#pragma once does the same and is widely supported but not in the standard. A header should include what it needs to be self-contained, and nothing more. Forward declare structs to cut dependencies. Compile each header on its own as a quick test. Include your own header first in its .c file, which proves it is self-contained.

Practice. Split a program into a module with a header and source file, add guards and prove the header compiles alone.

Macros, Predefined Macros and Conditional Compilation Core

#define creates a text substitution. Object-like macros define constants, and function-like macros take arguments. Macros do not respect types or scope, so follow the rules: parenthesise the parameters and the whole body, and avoid arguments with side effects because they may be evaluated more than once.

#define SQUARE(x) ((x) * (x))   /* SQUARE(i++) is a bug */
#define ARRAY_LEN(a) (sizeof (a) / sizeof (a)[0])

Prefer static inline functions and enum or const values when possible. Multi-statement macros are wrapped in do { ... } while (0). The operators # (stringise) and ## (paste) are used in advanced macros.

Predefined macros include __FILE__, __LINE__, __func__ (a variable, strictly), __DATE__ and __STDC_VERSION__. Conditional compilation with #if, #ifdef, #elif and #else selects code by platform or feature, and #error stops a build with a message. Keep conditionals few, as they multiply the paths you must test.

Practice. Write a LOG macro that prints file, line and a printf-style message, and a platform check that fails the build with #error.

Linking, Static and Shared Libraries and the ABI Core

The linker resolves each symbol reference to a definition. Libraries bundle object files. A static library (.a) is copied into the executable at link time. A shared library (.so, .dylib or .dll) is loaded at run time, so many programs share one copy and you can update it without relinking, but the program needs it present.

The ABI (application binary interface) is the machine-level contract: how arguments are passed, struct layouts, sizes and name mangling. Two pieces of code built with different compilers or options can only work together if they agree on the ABI. Changing a struct layout or a function signature in a shared library breaks existing binaries even if the source still compiles.

Useful tools: nm lists symbols, ldd (Linux) shows needed libraries, and objdump disassembles. Link order matters for static libraries: put libraries after the objects that use them.

Practice. Build a small static and a shared library from the same code and link a program against each.

Build Systems: GNU Make, CMake, Ninja and Meson Core

A build system rebuilds only what changed. GNU Make reads a Makefile of rules: a target, its dependencies and the commands to build it.

CC = cc
CFLAGS = -std=c17 -Wall -Wextra -g
app: main.o util.o
	$(CC) -o $@ $^
%.o: %.c util.h
	$(CC) $(CFLAGS) -c $< -o $@

Make is simple and everywhere, but you must track header dependencies yourself (use -MMD). CMake describes a project at a higher level and generates files for Make, Ninja or IDEs; it is the most widely used system for C and C++ libraries. Ninja is a very fast low-level builder designed to be generated by tools. Meson is a newer system with readable syntax that uses Ninja underneath. Pick CMake when you must fit existing projects, and Make for small ones.

Practice. Write a Makefile for a three-file project with automatic header dependencies, then port it to a minimal CMakeLists file.

Package Managers: Conan and vcpkg, and Structuring Codebase Recommended

C has no single standard package manager. Conan and vcpkg download, build and cache third-party libraries and integrate with CMake. On Linux, many people use the system package manager plus pkg-config to find flags for installed libraries. Vendoring (copying a dependency's source into your tree) is common for small libraries.

A sensible layout separates public headers from private code:

  • include/project/ for the public API
  • src/ for implementation and private headers
  • tests/ for unit tests
  • build/ for output, kept out of version control

Group code into modules with a clear header each, minimal global state and a naming prefix. Keep each .c file focused. Add a README with build steps, and run the compiler with warnings as errors in continuous integration. See Git and GitHub Roadmap for the version control side.

Practice. Add a third-party library to a CMake project through a package manager and call one function from it.

Stage 8 Standard Library, Errors and Files

Intermediate2 weeks4 topics

Goal. Use the standard library idiomatically, handle errors consistently and read and write files safely.

The Standard Library, Math & Time and Data Utilities Core

The C standard library is small. Know the headers: stdio.h (I/O), stdlib.h (allocation, conversions, qsort, bsearch, rand, exit), string.h, ctype.h, math.h, time.h, limits.h and float.h (type limits), stdint.h, stdbool.h, stddef.h, stdarg.h, signal.h, setjmp.h, assert.h and errno.h.

math.h functions work on double (with f and l variants for other types); link with -lm on many systems. time.h provides time, clock, difftime, strftime and localtime; it handles calendar time but not time zones in depth. rand is a weak generator and not suitable for security; use the operating system's source of random bytes for that. qsort and bsearch are the standard data utilities and take comparison callbacks.

Practice. Sort an array of structs by two keys with qsort and then find one with bsearch.

Error Handling, errno and assert.h Core

C has no exceptions. Functions signal failure through return values: a negative number, NULL, or a status code. Many library functions also set errno (from errno.h) to a code describing the failure. Read it immediately after the failing call, since other calls may overwrite it, and turn it into text with strerror or perror.

FILE *f = fopen(path, "r");
if (!f) {
    fprintf(stderr, "open %s: %s\n", path, strerror(errno));
    return -1;
}

Check every call that can fail: fopen, malloc, fread, fclose and system calls. Decide on a consistent convention across a project. Use assert from assert.h for programmer errors (conditions that must always be true); it aborts with a message and disappears when NDEBUG is defined, so never put side effects in it. Do not use assert to validate user input.

Practice. Write a function that returns distinct error codes and a caller that prints a useful message for each.

Diagnostics & Limits, and setjmp / longjmp Recommended

limits.h and float.h give constants like INT_MAX, UINT_MAX, CHAR_BIT and DBL_EPSILON. Use them to check for overflow before an operation rather than after: if (a > INT_MAX - b) is safe, a + b overflowing is not. C23 adds stdckdint.h with checked arithmetic functions, and compilers provide builtins such as __builtin_add_overflow.

setjmp saves the execution context and longjmp jumps back to it, unwinding the stack without running any cleanup. It is C's closest thing to exceptions and is used for error recovery in some libraries and parsers. Hazards: local variables changed after setjmp may have indeterminate values unless they are volatile, freed memory and open files are not cleaned up, and it makes code hard to follow. Prefer returning error codes and a single cleanup path.

Practice. Write a checked addition function that reports overflow, and a toy parser that uses setjmp to abort on error.

File I/O: Streams, File Pointers and Reading and Writing Files Core

stdio.h works with streams, each represented by a FILE *. Open with fopen(path, mode) where mode is "r", "w", "a" and so on, then use fgets, fputs, fprintf, fscanf, fread and fwrite, and close with fclose. Streams are buffered: data may sit in memory until the buffer fills, fflush is called or the file is closed. fclose can fail on write, so check its return value.

FILE *f = fopen("out.txt", "w");
if (!f) return -1;
fprintf(f, "total=%d\n", total);
if (fclose(f) != 0) return -1;

fseek, ftell and rewind move the position; feof and ferror tell you why a read stopped. Do not loop on feof alone; test the return value of the read call. Standard streams stdin, stdout and stderr are already open.

Practice. Copy a file in 4 KiB chunks with fread and fwrite and check every return value.

Stage 9 Debugging, Testing and Tooling

Intermediate2 weeks3 topics

Goal. Find memory and logic bugs quickly with debuggers and sanitizers, and protect code with automated tests.

Debugging with GDB, LLDB and WinDbg Core

Compile with -g and low optimisation, then use a debugger. GDB is standard on Linux; LLDB is the default with Clang and on macOS; WinDbg is the Windows debugger for native code and crash dumps.

Core commands in GDB: break file.c:42, run args, next (step over), step (step into), continue, print expr, backtrace, frame n, watch var (stop when a value changes), info locals and x/8xb ptr (examine memory). LLDB has equivalents with a slightly different syntax.

After a crash, a core file lets you inspect the state: run gdb ./prog core and type bt. Conditional breakpoints (break f if n == 7) save time in loops. Reading a backtrace is a skill interviewers value: find the first frame in your own code.

Practice. Debug a program that crashes on null dereference: get a backtrace, find the bad variable and fix it.

Valgrind, ASan & LSan and strace Core

Memory tools catch bugs the compiler cannot. AddressSanitizer (ASan), built with -fsanitize=address, detects out-of-bounds access, use after free and double free at run time with a small slowdown. LeakSanitizer (LSan) reports leaks and runs with ASan on supported platforms. UndefinedBehaviorSanitizer (-fsanitize=undefined) catches signed overflow and misaligned access.

Valgrind runs an unmodified binary in a virtual machine and reports invalid reads and writes and leaks; it is slower but needs no rebuild. It is mainly for Linux.

strace lists the system calls a process makes, which is a quick way to see which file a program fails to open, or where it blocks. Use these tools in every test run in continuous integration.

Practice. Build a program with an off-by-one write and a leak, then find both with ASan and Valgrind.

Testing with Unity, CMocka and Check Recommended

C has no built-in test framework, but several small ones exist. Unity is tiny and popular in embedded work. CMocka supports mock objects. Check runs each test in a separate process, so a crash fails one test rather than the whole run.

Basic style with Unity:

void test_add(void) {
    TEST_ASSERT_EQUAL_INT(5, add(2, 3));
}

Design for testing: keep logic in functions that take inputs and return outputs, avoid hidden globals and hide hardware or the operating system behind small interfaces that tests can replace. Build tests with sanitizers on. Test error paths too, for example by making an allocation wrapper fail on purpose. Fuzzing with a coverage-guided tool is very effective for parsers.

Practice. Write five unit tests for your dynamic array, including growth and an out-of-memory path with a fake allocator.

Stage 10 Systems Programming and Idioms

Advanced3 weeks3 topics

Goal. Write processes and threads that cooperate safely, and apply C idioms for structure, cleanup and portability.

Process Management, IPC and Signals Recommended

On POSIX systems, fork creates a copy of the calling process, exec replaces its program, and wait collects the child's exit status. A shell is essentially this loop. Not collecting children leaves zombie processes.

Inter-process communication (IPC) offers pipes (pipe, popen), named pipes, sockets, shared memory (shm_open, mmap), message queues and semaphores. Pipes and sockets are the most common.

Signals are asynchronous notifications such as SIGINT, SIGTERM and SIGSEGV. Use sigaction rather than signal. A handler may call only async-signal-safe functions; commonly it sets a volatile sig_atomic_t flag and returns, and the main loop reacts. These OS and signal interfaces are POSIX, not part of ISO C, so Windows uses different calls. See Linux Roadmap for the operating system side.

Practice. Write a program that forks a child to run a command, waits for it and prints its exit status, and handles SIGINT cleanly.

Concurrency, POSIX Threads and Mutexes Recommended

Threads share an address space, so they can race: two threads touching the same data with at least one write and no synchronisation is a data race and undefined behaviour. POSIX threads (pthread_create, pthread_join) are the standard API on Unix-like systems; C11 defines threads.h as an optional alternative.

A mutex protects shared data:

pthread_mutex_lock(&m);
counter++;
/* release with the matching call */

Lock for as short a time as possible, acquire multiple locks in one fixed order to avoid deadlock, and use a condition variable (pthread_cond_wait) to wait for a state change. _Atomic types and stdatomic.h give lock-free operations for simple cases, with memory-ordering options. Test with ThreadSanitizer (-fsanitize=thread), which finds races that tests rarely show.

Practice. Start four threads that each increment a shared counter a million times, observe the race, then fix it with a mutex and with an atomic.

Idioms and Design Patterns, Object-Oriented C and RAII-Simulated Cleanup Recommended

Experienced C programmers rely on a few idioms. For error paths, use a single cleanup label with goto so resources are released in reverse order:

int run(void) {
    int rc = -1;
    FILE *f = fopen("in", "r");
    if (!f) goto out;
    char *buf = malloc(4096);
    if (!buf) goto close_f;
    /* work */
    rc = 0;
    free(buf);
close_f:
    fclose(f);
out:
    return rc;
}

This simulates RAII (resource cleanup tied to scope). GCC and Clang also offer __attribute__((cleanup)) for scope-based cleanup, but it is not standard.

Object-oriented C uses structs plus function pointers: a struct of function pointers acts as a vtable, and opaque handles give encapsulation. Other patterns: init/destroy pairs, "create returns new object" naming, tagged unions for variants and callbacks with user data.

Practice. Refactor a function with nested error checks to use a single cleanup path, and build a shape interface with a function pointer table.

Projects to build

Build these in order. Each one should end up in a public repository with a short README that explains your decisions.

  1. Command-line word counterBeginner

    Write a tool like wc that counts lines, words and bytes in files or standard input, with flags to choose which to show. Return correct exit codes and print errors to standard error.

    Command-line arguments · File I/O · Strings · Exit codes

  2. Dynamic array and hash map libraryIntermediate

    Build a small library with a header, a source file and unit tests: a growable array and a string-keyed hash map with resizing. Hide the structs behind opaque pointers and run the tests under sanitizers.

    Opaque pointers · malloc and realloc · Hashing · Unit tests

  3. Tiny shellIntermediate

    Write a shell that reads a line, splits it into words, runs the command with fork and exec, supports cd and a simple pipe between two commands and handles Ctrl+C without exiting.

    Process management · Pipes · Signals · String parsing

  4. Key-value store with a file formatAdvanced

    Create an in-memory store that saves to disk in a binary format with a magic number, version and checksum. Add a command-line client. Handle partial writes by writing to a temporary file and renaming it.

    Binary files · Hash maps · Error handling · Portable formats

  5. Multi-threaded work queueAdvanced

    Implement a thread pool with a bounded queue protected by a mutex and condition variables, then use it to compute checksums of many files in parallel. Verify with ThreadSanitizer and measure the speed-up.

    POSIX threads · Mutexes · Condition variables · Ring buffers

Interview questions

Try to answer each question out loud before you open the answer.

What is the difference between a pointer and an array?Junior

An array is a block of elements with a fixed size; the name stands for the whole block, and sizeof gives its total size. A pointer is a variable holding an address, with its own size. In most expressions an array name decays to a pointer to its first element, which is why a[i] equals *(a + i). Function parameters declared as arrays are really pointers, so the length must be passed separately.

What does `static` mean in C?Junior

It has two uses. On a local variable it gives static storage duration: the variable is created once and keeps its value between calls. On a file-scope function or variable it gives internal linkage, so the name is invisible to other translation units. Both uses limit visibility or lifetime on purpose, and the second is how C modules keep helpers private.

Explain the difference between the stack and the heap.Junior

The stack holds local variables and call frames; allocation is automatic and fast, and memory is freed when the function returns, but the stack is small and has a fixed limit. The heap is for memory requested with malloc that lives until you call free; it can be large and outlive the function but needs manual management and can leak or fragment. Returning the address of a stack variable is a bug.

Why is `a = realloc(a, n)` a problem?Junior

If realloc fails it returns NULL and leaves the original block allocated. Assigning the result straight to a overwrites the only pointer to that block, so it leaks and the program also loses its data. Store the result in a temporary, check it, and only then assign it back to a. On failure, free the original or handle the error as the program requires.

What is undefined behaviour and why does it matter?Mid

The standard imposes no requirements on a program that triggers it: the result may be a crash, a wrong answer or something that appears to work. Compilers assume it never happens, so they can remove checks or reorder code, and a bug may only appear at a higher optimisation level or on another compiler. Examples are signed overflow, out-of-bounds access, use after free and reading uninitialised variables. Sanitizers and warnings are the main defence.

How does `volatile` differ from atomic operations?Mid

volatile forces the compiler to perform each access to the object, which is needed for hardware registers and for objects changed by signal handlers. It does not make an operation indivisible and gives no ordering between threads, so it cannot replace synchronisation. For shared data between threads use a mutex or _Atomic types, which provide indivisible operations and defined memory ordering.

How would you find a memory leak and a buffer overflow?Mid

I would build with AddressSanitizer and LeakSanitizer and run the tests; they report the allocation site of a leak and the exact access for an overflow. If rebuilding is not possible, I would run Valgrind on the binary. For a crash without tooling I use a debugger with a backtrace and watchpoints. After the fix I add a test that would have caught the problem and keep sanitizers enabled in continuous integration.

Why are function-like macros dangerous, and what do you use instead?Mid

Macros are text substitution, so arguments may be evaluated more than once, precedence can change meaning unless everything is parenthesised, there is no type checking and debuggers see the expanded code. For example SQUARE(i++) increments twice. Prefer static inline functions for code, and enum or const for constants. Keep macros for things functions cannot do, such as stringising, conditional compilation or capturing __FILE__ and __LINE__.

How would you implement a stack-safe string copy?Mid

I would know the destination size and the source length, then check that the source plus terminator fits before copying with memcpy, or use snprintf with the buffer size and test the returned length for truncation. strcpy is unsafe because it cannot know the limit, and strncpy may leave the result unterminated and pads with zeros. Decide the policy on truncation (fail or cut) and make it explicit.

What happens when you call `free` twice on the same pointer?Mid

It is undefined behaviour. The allocator's internal lists can be corrupted, which can crash later in an unrelated call or be exploited by an attacker. Prevent it with clear ownership: one owner frees, and sets the pointer to NULL afterwards so a repeat call is harmless. AddressSanitizer reports double free with both stack traces.

Reverse a singly linked list in place.Junior

Keep three pointers: prev starts as NULL, cur is the head and next saves the following node. In a loop, save cur->next, point cur->next at prev, then move prev to cur and cur to the saved node. When cur is NULL, prev is the new head. It takes O(n) time and O(1) extra space. Test with an empty list, one node and two nodes.

What is strict aliasing and how do you reinterpret bytes safely?Senior

The rule says an object may be accessed only through an lvalue of a compatible type, a character type, or a few other allowed types. Reading a float through an int * breaks it and the optimiser may reorder or drop the access. To reinterpret bytes safely, copy them with memcpy into an object of the target type, which compilers turn into a single move, or use a union where the standard permits it.

How do you avoid deadlock in a multi-threaded C program?Senior

Always acquire multiple mutexes in one global order, hold locks for as little time as possible and avoid calling unknown code, such as callbacks, while holding a lock. Use trylock with back-off where order cannot be fixed. Prefer designs with fewer shared objects: message queues, per-thread data, or atomics for simple counters. ThreadSanitizer reports lock-order inversions during tests.

Design a ring buffer for an interrupt handler that writes bytes and a main loop that reads them.Senior

Use a power-of-two array with a head index written only by the producer and a tail index written only by the consumer, so no lock is needed. Make the indexes atomic or volatile as the platform requires, and make the producer write the data before publishing the new head. Keep one slot empty to tell full from empty, drop or count overflow bytes and test wraparound explicitly.

Common mistakes

  • Assuming int is 32 bits or that char is signed; use the stdint.h types when size matters.
  • Using sizeof on an array parameter, which gives the pointer size; pass the length as another argument.
  • Forgetting that malloc can fail and not checking for NULL; check every allocation and handle it.
  • Using gets, strcpy or scanf("%s") without limits; use fgets, snprintf and bounded copies.
  • Returning a pointer to a local variable; return allocated memory, a static object or write into a caller buffer.
  • Ignoring compiler warnings; compile with -Wall -Wextra and treat warnings as errors in CI.
  • Comparing floating-point values with ==; compare against a tolerance suited to the problem.
  • Letting switch cases fall through by accident; end each case with break and mark deliberate fall-through.
  • Testing only with optimisation off; run tests at the release level too, and with sanitizers.
  • Leaving ownership unclear so memory leaks or is freed twice; write down who frees each allocation.

Ready-for-interview checklist

  • I can explain the four stages from source file to executable.
  • I can write and read pointer declarations, including pointers to pointers and function pointers.
  • I can explain array decay and why arrays need an explicit length.
  • I can allocate, resize and free memory correctly and check for failure.
  • I can name five kinds of undefined behaviour and how to detect them.
  • I can implement a linked list, a dynamic array and a hash map from scratch.
  • I can split a program into headers and sources with include guards and opaque types.
  • I can write a Makefile or CMake file for a multi-file project.
  • I can use a debugger to get a backtrace and set a watchpoint.
  • I can run AddressSanitizer, LeakSanitizer and Valgrind and read their reports.
  • I can read and write files with full error checking and explain buffering.
  • I can protect shared data with a mutex and explain a data race.

Related roadmaps

FAQ

How long does it take to learn C?

Most people can write small programs after two to three weeks. Becoming comfortable with pointers and memory usually takes two to three months of regular practice, and reaching interview level, including debugging and a few data structure implementations, takes about four to five months at around eight hours a week.

Should I learn C before C++ or Rust?

It is not required, but C is a good first step because it shows what memory and the machine are doing without extra features. That understanding makes C++ and Rust easier to learn. If your goal is application software rather than systems work, you can start with another language and return to C later.

Is C still worth learning?

Yes for systems, embedded, kernel, driver and performance roles, and for reading the large existing codebases such as operating systems and databases. It is also useful for understanding how other languages and runtimes work. Newer languages are replacing it for some new projects, but a great deal of C remains in use and needs maintenance.

Which C standard should I learn?

Learn C11 or C17 first, since they are widely supported, and then read about what C99 and C23 added. Your compiler flag decides which one you use, and codebases often fix it. Know the differences from older C89 code because you will meet it.

What is the best way to practise C?

Write small programs and data structures from scratch, run them under sanitizers and a debugger, and read open-source C. Reimplementing standard functions such as strlen, memcpy and qsort, and building a tiny shell or allocator, teaches the most.

Practise while you learn.Solve interview problems in the browser, with hints and a timer.
CodingSQLSystem design
Next Post Previous Post
No Comment
Add Comment
comment url