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
assertand switching them off withNDEBUG - 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 inmainshows what callingaverage(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
-DNDEBUGremoves everyassert, so release builds pay nothing for them. TheDEBUGmacro follows the same rule: it prints only whenNDEBUGis 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 exampleint total = 0;. - Bug 2, off by one:
i < nwould 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', sostrcpywrites 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.
fopenreturnsNULLwhen it fails, andstrerror(errno)turns the error code into a readable reason.
Tools That Find Bugs for You
| Tool | Command (GCC or Clang) | Finds |
|---|---|---|
| Warnings | gcc -Wall -Wextra prog.c | Unused variables, suspicious conversions, missing returns, many uninitialised variables |
| AddressSanitizer | gcc -g -fsanitize=address prog.c | Buffer overflows, use after free, memory leaks |
| UndefinedBehaviorSanitizer | gcc -g -fsanitize=undefined prog.c | Signed overflow, bad shifts, misaligned pointers |
| GDB debugger | gcc -g prog.c, then gdb ./a.out | Lets you stop at a line, step through code and inspect variables |
| Valgrind (Linux) | valgrind ./a.out | Memory 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
- Putting work inside an
assert, such asassert(fclose(f) == 0). WithNDEBUGthe whole call disappears and the file is never closed. - Using
assertto check user input. Users can type anything; handle it with an error message instead. - Ignoring warnings because the program “still compiles”. Many warnings point to real bugs.
- 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
assertcatches broken assumptions at run time;NDEBUGremoves asserts.static_assertcatches 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.
