Skip to content

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.

Beginner 16 min read·Lesson 36 of 37 in C Programming

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

SymptomLikely cause
expected ';' before ...missing semicolon on the previous line
undeclared identifiertypo, missing declaration or missing #include
undefined reference to ffunction declared but not defined or file not linked
multiple definition of xvariable or function defined in a header
Segmentation faultNULL/wild pointer, array out of bounds, stack overflow
Garbage numbersuninitialised variable, wrong printf specifier
Loop never endscondition never false, update skipped by continue
Result off by one<= vs <, wrong starting index
Works sometimesundefined behaviour (overflow, use after free, race)

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

Terminal
gcc -std=c11 -Wall -Wextra -Werror -g prog.c -o prog # strict build
gcc -std=c11 -g -fsanitize=address,undefined prog.c -o prog # test build
gdb ./prog # (gdb) break main | run | next | print x | backtrace
  • Build with sanitizers while testing and without them for release.
  • backtrace in 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

C
#include <stdio.h>
int main(void) {
int marks[] = {50, 60, 70};
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += marks[i];
printf("debug: i=%d sum=%d\n", i, sum);
}
printf("average %.1f\n", sum / 3.0);
return 0;
}
Output
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

C
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(1000 * sizeof *p);
if (p == NULL) {
fprintf(stderr, "out of memory\n");
return EXIT_FAILURE;
}
p[999] = 1;
printf("last element = %d\n", p[999]);
free(p);
return EXIT_SUCCESS;
}
Output
last element = 1

More examples

Five bugs, fixed

C
#include <stdio.h>
#include <string.h>
/* Each function is the corrected version of a classic bug (described in comments). */
/* 1. Off-by-one: the loop used i <= n. */
int sum(const int *a, int n) {
int s = 0;
for (int i = 0; i < n; i++) s += a[i];
return s;
}
/* 2. Integer division: avg was total / n with ints. */
double average(const int *a, int n) { return n ? (double)sum(a, n) / n : 0.0; }
/* 3. String compare with ==: now uses strcmp. */
int is_admin(const char *user) { return strcmp(user, "admin") == 0; }
/* 4. Buffer overflow with strcpy: now bounded. */
void set_name(char *dst, size_t size, const char *src) { snprintf(dst, size, "%s", src); }
/* 5. Missing break in switch: each case now ends with break. */
const char *level(int code) {
switch (code) {
case 1: return "low";
case 2: return "medium";
default: return "high";
}
}
int main(void) {
int a[] = {3, 4, 5};
char name[8];
char user[] = "admin";
set_name(name, sizeof name, "Bhavanishankar");
printf("sum=%d avg=%.2f\n", sum(a, 3), average(a, 3));
printf("admin? %d\n", is_admin(user));
printf("name='%s' (truncated safely)\n", name);
printf("level(2)=%s\n", level(2));
return 0;
}
Output
sum=12 avg=4.00
admin? 1
name='Bhavani' (truncated safely)
level(2)=medium

Step-by-step explanation

  • sum uses i < n, so it reads exactly the n valid elements.
  • average converts to double before dividing and guards against n == 0.
  • is_admin compares characters with strcmp; == would compare addresses and fail for a copied string like user.
  • snprintf writes 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:

TextOutput
sum=12 avg=4.00
admin? 1
name='Bhavani' (truncated safely)
level(2)=medium

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

/* 30 errors reported; you edit line 80 */

Prefer

/* fix the first error at line 12, recompile, repeat */

One missing brace or semicolon cascades into dozens of misleading messages. Always start at the top.

Ignoring warnings

Avoid

gcc prog.c -o prog # warnings hidden

Prefer

gcc -Wall -Wextra prog.c -o prog

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

  1. 1
    Take any program from this course, introduce an out-of-bounds write, and run it with -fsanitize=address. Read the report and identify the line.
  2. 2
    Use gdb to step through the recursive factorial and print n at 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;`?
Practise this topic