Reading history

assert and Debugging Techniques in C

6 min read 0 views

Catch C bugs early with assert, NDEBUG, static_assert and debug macros, fix three silent bugs, and use warnings, sanitizers and GDB.

Every programmer writes bugs. What separates beginners from experienced developers is how quickly they find them. C gives you tools to catch mistakes early: assert stops the program the moment an assumption is broken, static_assert checks things before the program even runs, and macros such as __func__ and __LINE__ tell you exactly where something happened. This lesson covers those tools, three classic bugs, and the compiler options and debuggers that find the rest.

In this lesson you will learn

  • Run-time checks with assert and switching them off with NDEBUG
  • Compile-time checks with static_assert
  • A debug-print macro using __func__ and __LINE__
  • Three common bugs that compile without errors
  • Compiler warnings, sanitizers and the GDB debugger

You should know macros, error handling and undefined behaviour.

assert, static_assert and Debug Prints

#include <stdio.h>
#include <assert.h>
#include <limits.h>

/* static_assert is checked by the compiler: a false one stops the build */
static_assert(sizeof(int) >= 4, "this program needs 32-bit int");
static_assert(CHAR_BIT == 8, "bytes must be 8 bits");

/* assert checks something that must be true if the code is correct */
int average(const int *a, int n) {
    assert(a != NULL);
    assert(n > 0);              /* a caller passing 0 items is a bug */
    long sum = 0;
    for (int i = 0; i < n; i++) sum += a[i];
    return (int)(sum / n);
}

/* A debug-print macro that shows where it was called from */
#ifdef NDEBUG
#define DEBUG(...) ((void)0)
#else
#define DEBUG(...) (printf("[%s, line %d] ", __func__, __LINE__), \
                    printf(__VA_ARGS__), putchar('\n'))
#endif

int find_max_index(const int *a, int n) {
    int best = 0;
    for (int i = 1; i < n; i++) {
        if (a[i] > a[best]) {
            best = i;
            DEBUG("new best at index %d (value %d)", i, a[i]);
        }
    }
    return best;
}

int main(void) {
    int marks[] = {62, 78, 71, 90, 85};
    int n = sizeof marks / sizeof marks[0];
    printf("average: %d\n", average(marks, n));
    printf("max at index %d\n", find_max_index(marks, n));
    /* average(marks, 0) would stop the program with a message like:
       prog: dbg1.c:12: average: Assertion `n > 0' failed. */
    return 0;
}

Output

average: 77
[find_max_index, line 31] new best at index 1 (value 78)
[find_max_index, line 31] new best at index 3 (value 90)
max at index 3
  • static_assert(condition, "message") is checked by the compiler. If the condition is false, the build stops with your message, so the program never runs on a system that does not meet its needs. In C11 it comes from <assert.h>; C23 makes it a keyword.
  • assert(n > 0) is checked while the program runs. If it is false, the program prints the file, line, function and failed condition, then stops. The comment in main shows what calling average(marks, 0) would print.
  • Asserts are for programming mistakes, conditions that can only be false if the code itself is wrong. They are not for user input or missing files, which a correct program must expect and handle.
  • Compiling with -DNDEBUG removes every assert, so release builds pay nothing for them. The DEBUG macro follows the same rule: it prints only when NDEBUG is not defined.
  • __func__ holds the current function’s name and __LINE__ the line number, so each debug message shows exactly where it came from. __FILE__ gives the file name in the same way.

Three Silent Bugs and Checking Results

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

/* Three bugs that compile cleanly; each is fixed and explained */

int sum_to(int n) {
    int total = 0;                  /* bug 1 was: int total; (uninitialised) */
    for (int i = 1; i <= n; i++)    /* bug 2 was: i < n (off by one) */
        total += i;
    return total;
}

char *copy_name(const char *src) {
    char *dst = malloc(strlen(src) + 1);   /* bug 3 was: malloc(strlen(src)) */
    if (dst) strcpy(dst, src);
    return dst;
}

int main(void) {
    printf("sum 1..10 = %d (expected 55)\n", sum_to(10));

    char *name = copy_name("Chattogram");
    if (!name) return 1;
    printf("copied: %s (%zu chars)\n", name, strlen(name));
    free(name);

    /* Checking return values is the cheapest debugging of all */
    FILE *f = fopen("/no/such/folder/data.txt", "r");
    if (f == NULL) {
        printf("could not open data.txt: %s\n", strerror(errno));
    } else {
        fclose(f);
    }
    return 0;
}

Output

sum 1..10 = 55 (expected 55)
copied: Chattogram (10 chars)
could not open data.txt: No such file or directory
  • Bug 1, an uninitialised variable: int total; starts with whatever was in memory, so the sum is garbage and may change between runs. Always initialise, for example int total = 0;.
  • Bug 2, off by one: i < n would stop at 9 and print 45 instead of 55. Test with small inputs whose answers you know.
  • Bug 3, a missing byte: malloc(strlen(src)) leaves no room for '\0', so strcpy writes one byte past the block. The program may still seem to work, which is what makes this bug dangerous.
  • Checking every return value is the cheapest debugging there is. fopen returns NULL when it fails, and strerror(errno) turns the error code into a readable reason.

Tools That Find Bugs for You

ToolCommand (GCC or Clang)Finds
Warningsgcc -Wall -Wextra prog.cUnused variables, suspicious conversions, missing returns, many uninitialised variables
AddressSanitizergcc -g -fsanitize=address prog.cBuffer overflows, use after free, memory leaks
UndefinedBehaviorSanitizergcc -g -fsanitize=undefined prog.cSigned overflow, bad shifts, misaligned pointers
GDB debuggergcc -g prog.c, then gdb ./a.outLets you stop at a line, step through code and inspect variables
Valgrind (Linux)valgrind ./a.outMemory errors and leaks without recompiling

Running bug 3 under AddressSanitizer reports a “heap-buffer-overflow” with the exact line, even though the normal build seems fine. In GDB, the commands break average, run, next, print sum and backtrace cover most everyday debugging.

Common Mistakes

  1. Putting work inside an assert, such as assert(fclose(f) == 0). With NDEBUG the whole call disappears and the file is never closed.
  2. Using assert to check user input. Users can type anything; handle it with an error message instead.
  3. Ignoring warnings because the program “still compiles”. Many warnings point to real bugs.
  4. Debugging with prints only and leaving them in the final code. Use a macro that can be switched off, or a debugger.

Practice Exercises

Exercise 1. Add an assert to a function int get(const int *a, int n, int i) so it catches an out-of-range index.

Show answer
int get(const int *a, int n, int i) {
    assert(a != NULL);
    assert(i >= 0 && i < n);
    return a[i];
}

Exercise 2. Use static_assert to make sure a struct used in a file format is exactly 16 bytes.

Show answer
#include <assert.h>
#include <stdint.h>

typedef struct { uint32_t id; uint32_t date; uint64_t amount; } Record;
static_assert(sizeof(Record) == 16, "Record must be 16 bytes");

Frequently Asked Questions

Should I leave asserts on in the finished program?

Opinions differ. Many teams disable them in release builds for speed. Others keep them on, because stopping with a clear message is better than continuing with corrupted data. Either way, never rely on an assert for normal error handling.

What is rubber duck debugging?

Explaining your code, line by line, to someone else, even a rubber duck on your desk. Saying what each line should do often reveals the line that does something different.

Summary

  • assert catches broken assumptions at run time; NDEBUG removes asserts.
  • static_assert catches problems at compile time.
  • Initialise variables, test edge cases and check every return value.
  • Use -Wall -Wextra, sanitizers and GDB to find what tests miss.

Next: C Project: Word Frequency Counter.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *