TExcelTAD
Home › C › C Errors & Debugging

C Errors & Debugging

Every programmer writes bugs; good programmers find them quickly. In C, problems show up at three different stages, and each needs different tools: compile-time errors, runtime errors, and logic errors. This lesson shows how to recognise each kind and how to handle errors gracefully in your own code.

1. Compile-time errors

The compiler refuses to build the program and tells you where and why. Typical causes:

c
#include <stdio.h>

int main(void) {
    int count = 5
    printf("%d\n", cuont);
    return 0;
}
text
prog.c: In function 'main':
prog.c:5:5: error: expected ',' or ';' before 'printf'
prog.c:5:20: error: 'cuont' undeclared (first use in this function); did you mean 'count'?
Message fragment Usual cause
expected ';' before … missing semicolon on the previous line
undeclared (first use in this function) typo in a name, or variable declared in another scope
implicit declaration of function missing #include or prototype
incompatible types when assigning assigning e.g. a string to an int
expected declaration or statement at end of input a missing }

Tip: Fix the first error first and recompile. One mistake often triggers a cascade of follow-up messages that disappear with it.

Warnings are bugs waiting to happen

Warnings do not stop compilation, but many point to real problems. Compile with -Wall -Wextra (and -Werror to turn warnings into errors in serious projects):

c
int x;
if (x = 10) { }          // warning: suggest parentheses around assignment used as truth value
printf("%d\n", 3.5);     // warning: format '%d' expects 'int', but argument has type 'double'
int total;               // warning: 'total' is used uninitialized
return total + 1;

2. Runtime errors

The program compiles, but crashes or misbehaves while running. Common culprits in C:

Symptom Likely cause
Segmentation fault dereferencing NULL or an invalid pointer, out-of-bounds array access, stack overflow
Floating point exception integer division by zero
garbage values uninitialised variables, reading freed memory
double free or corruption calling free twice, writing past an allocated block

Many of these are undefined behaviour: the program may crash, print nonsense, or appear to work — until it doesn't. Sanitizers catch them reliably: compile with gcc -g -fsanitize=address,undefined prog.c and the program stops at the exact faulty line with a detailed report.

3. Logic errors

The program runs without complaint but gives the wrong answer. The compiler cannot help here. Classic examples:

c · try it yourself
#include <stdio.h>

int main(void) {
    int scores[] = {70, 85, 90};
    int n = 3;

    // Bug 1: integer division loses the fraction
    int sum = 0;
    for (int i = 0; i < n; i++) sum += scores[i];
    printf("average (buggy): %d\n", sum / n);
    printf("average (fixed): %.2f\n", (double) sum / n);

    // Bug 2: off-by-one — "i < n - 1" skips the last element
    int max_buggy = scores[0];
    for (int i = 0; i < n - 1; i++) if (scores[i] > max_buggy) max_buggy = scores[i];
    int max_fixed = scores[0];
    for (int i = 0; i < n; i++) if (scores[i] > max_fixed) max_fixed = scores[i];
    printf("max (buggy): %d, max (fixed): %d\n", max_buggy, max_fixed);
    return 0;
}
average (buggy): 81
average (fixed): 81.67
max (buggy): 85, max (fixed): 90

Debugging techniques

  • Print debugging: add temporary printf statements showing variable values. Print to stderr with fprintf(stderr, ...) so the messages are not buffered and do not mix with normal output.
  • A debugger: compile with -g and run gdb ./prog. Set breakpoints (break main), step line by line (next, step), and inspect variables (print x). IDEs offer the same with buttons.
  • Assertions: assert(condition) from <assert.h> stops the program with a message if a condition you believe is always true turns out false.
  • Shrink the problem: remove code until the bug disappears; the last thing removed is a suspect.
c
#include <assert.h>

double average(const int *values, int n) {
    assert(values != NULL);
    assert(n > 0);            // dividing by zero would be a bug in the caller
    ...
}
text
prog: prog.c:5: average: Assertion `n > 0' failed.
Aborted

Assertions are removed when you compile with -DNDEBUG, so use them for programmer mistakes, not for checking user input.

Handling errors in your program

C has no exceptions. Functions report failure through their return value, and you are expected to check it. Many library functions also set the global variable errno (from <errno.h>), and strerror(errno) turns it into a readable message:

c · try it yourself
#include <stdio.h>
#include <string.h>
#include <errno.h>

int main(void) {
    FILE *fp = fopen("this-file-does-not-exist.txt", "r");
    if (fp == NULL) {
        printf("Could not open file: %s (errno %d)\n", strerror(errno), errno);
    } else {
        fclose(fp);
    }
    return 0;
}
Could not open file: No such file or directory (errno 2)

perror("fopen") is a shortcut that prints the same message, prefixed with your text, to stderr.

Your own functions can follow the same convention: return a status code, and pass results back through pointer parameters:

c · try it yourself
#include <stdio.h>

typedef enum { OK = 0, ERR_EMPTY, ERR_RANGE } Status;

const char *status_text(Status s) {
    switch (s) {
        case OK:        return "ok";
        case ERR_EMPTY: return "no values given";
        case ERR_RANGE: return "value out of range 0..100";
    }
    return "unknown error";
}

Status average_percent(const int *v, int n, double *out) {
    if (n <= 0) return ERR_EMPTY;
    int sum = 0;
    for (int i = 0; i < n; i++) {
        if (v[i] < 0 || v[i] > 100) return ERR_RANGE;
        sum += v[i];
    }
    *out = (double) sum / n;
    return OK;
}

int main(void) {
    int good[] = {50, 75, 100};
    int bad[] = {50, 175};
    double avg;

    Status s = average_percent(good, 3, &avg);
    if (s == OK) printf("average: %.1f\n", avg);

    s = average_percent(bad, 2, &avg);
    if (s != OK) printf("error: %s\n", status_text(s));

    s = average_percent(good, 0, &avg);
    if (s != OK) printf("error: %s\n", status_text(s));
    return 0;
}
average: 75.0
error: value out of range 0..100
error: no values given

Finally, main's return value is the program's exit status: return 0 (or EXIT_SUCCESS) on success and a non-zero value (EXIT_FAILURE) on failure, so scripts calling your program can tell what happened.

Test yourself

What kind of error is a missing semicolon?

  1. Runtime error
  2. Logic error
  3. Compile-time error
  4. Linker error

A program compiles and runs but prints the wrong total. What kind of error is this?

  1. Compile-time error
  2. Logic error
  3. Syntax error
  4. Preprocessor error

How do standard C library functions usually report errors?

  1. By throwing exceptions
  2. Through return values and often by setting errno
  3. By printing to the screen only
  4. They never fail