Module 9 · Bitwise Operations, Common Errors and Applications — topic 2 of 3
Common Programming Errors
A field guide to the bugs that most often break C programs — compile errors, link errors, runtime crashes and silent undefined behaviour — with the compiler flags and tools that find them.
Learning objectives
- Classify an error as compile, link, runtime or undefined behaviour
- Recognise the ten most common C bugs from their symptoms
- Use -Wall, sanitizers and a debugger to locate faults
Definition
Programming errors fall into syntax/compile-time errors (rejected by the compiler), link-time errors (unresolved or duplicate symbols), run-time errors (crashes, wrong results) and undefined behaviour — operations for which the C standard imposes no requirements.
Introduction
Every C programmer makes the same mistakes while learning. The difference between a frustrated beginner and a productive one is recognising the symptoms quickly and knowing which tool to reach for.
C's most dangerous errors are the ones that don't produce an error message: undefined behaviour may appear to work on your laptop and fail in the lab, in the exam, or months later in production.
Why it matters
Debugging consumes more time than writing code. A checklist of likely causes, and the habit of compiling with warnings and sanitizers, cuts that time dramatically.
“Find the error in this code” is one of the most common question types in exams and in this course's practice bank.
Detailed explanation
Compile errors are reported with a file and line; fix the first error first, because later ones are often consequences of it.
Warnings (-Wall -Wextra) flag likely bugs: assignments in conditions, format mismatches, unused variables, missing returns, implicit conversions. Treat them as errors with -Werror in your own projects.
Runtime tools: -fsanitize=address catches out-of-bounds and use-after-free; -fsanitize=undefined catches signed overflow, invalid shifts and null dereferences; gdb ./prog lets you run, set breakpoints (break main), step (next, step) and inspect variables (print x). Compile with -g for debug information.
Undefined behaviour includes: signed overflow, reading uninitialised locals, out-of-bounds access, dereferencing NULL or freed memory, modifying a variable twice between sequence points, and data races. The compiler may assume it never happens and optimise accordingly.
Syntax
- Build with sanitizers while testing and without them for release.
backtracein gdb shows the chain of calls that led to a crash.- Reproduce the bug with the smallest possible input before fixing it.
Code examples
A logic error found by printing
debug: i=0 sum=50 debug: i=1 sum=110 debug: i=2 sum=180 average 60.0
Temporary debug prints confirm each step; remove them (or guard them with a DEBUG macro) when done.
Checking results instead of assuming them
last element = 1
More examples
Five bugs, fixed
sum=12 avg=4.00 admin? 1 name='Bhavani' (truncated safely) level(2)=medium
Step-by-step explanation
sumusesi < n, so it reads exactly the n valid elements.averageconverts todoublebefore dividing and guards againstn == 0.is_admincompares characters withstrcmp;==would compare addresses and fail for a copied string likeuser.snprintfwrites at most 7 characters plus the terminator into the 8-byte buffer, so the long name is cut to "Bhavani" instead of overflowing.- Returning from each case avoids fall-through entirely.
Expected output
Running “Five bugs, fixed” prints exactly:
Practical applications
- Heartbleed (2014) was a missing bounds check in OpenSSL's C code.
- Professional teams build every commit with warnings-as-errors and sanitizers in CI.
- Static analysers (cppcheck, clang-tidy) scan C code for these patterns automatically.
Best practices
- Compile often, with
-Wall -Wextra, and fix warnings immediately. - Test with sanitizers and with boundary inputs (0, 1, maximum, empty).
- Learn five gdb commands: break, run, next, print, backtrace.
Common mistakes
Fixing the last error message first
Avoid
Prefer
One missing brace or semicolon cascades into dozens of misleading messages. Always start at the top.
Ignoring warnings
Avoid
Prefer
Many crashes and wrong results are announced by a warning you never asked to see.
Important notes
- Undefined behaviour can “time travel”: an optimiser may remove a check that appears before the undefined operation, because it assumes the operation never happens.
- Different compilers and optimisation levels can turn the same undefined code into different results — never rely on what it did once.
Key takeaways
- Know the four error classes: compile, link, runtime, undefined behaviour.
- Fix the first compiler error first; never ignore warnings.
- Use sanitizers and gdb to locate runtime faults.
Try it yourself
- 1Take any program from this course, introduce an out-of-bounds write, and run it with
-fsanitize=address. Read the report and identify the line. - 2Use gdb to step through the recursive factorial and print
nat each level.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
3 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerA program compiles but crashes with “Segmentation fault”. Which is a likely cause?
- ModerateA function sometimes returns garbage. `-Wall` reports “'total' may be used uninitialized”. What is the fix?
- AdvancedWhy can an optimising compiler delete the check in `if (p->len > 0 && p == NULL) return;` placed after `int n = p->len;`?