ZetCode

Debugging K&R C

last modified December 5, 2026 K&R C 1978

A K&R C compiler checks little. It accepts calls with the wrong arguments, assignments where comparisons were meant, and variables that are used before they get a value. Most mistakes compile and run, and they show only as wrong results or crashes. This article shows the tools that find them: the warnings of GCC, the lint program that UNIX had for this purpose, and the debuggers gdb on Linux and adb on the PDP-11.

Bugs that compile

The next program has four bugs. Without options, GCC compiles it without a word.

buggy.c
#include <stdio.h>

int count(s)
char *s;
{
    int n;

    while (*s++ != '\0')
        n++;
    return n;
}

int sign(x)
int x;
{
    if (x = 0)
        return 0;
    if (x > 0)
        return 1;
}

int main()
{
    long big;

    big = 100000L;
    printf("%d %d\n", count("tide"), sign(-5));
    printf("%d\n", big);
    return 0;
}

count never sets n to zero before it counts. sign tests x = 0, an assignment, instead of x == 0, and it has no return for a negative number. The last printf prints a long with %d. The program prints 4 for "tide", because n happened to start at zero, and 0 for the sign of -5, because the assignment set x to zero. The long is printed right by accident: x86-64 passes it in a register, and %d reads its lower half.

$ gcc -std=c89 -o buggy buggy.c
$ ./buggy
4 0
100000

Turning on the warnings

All examples of this series are compiled with -Wall and -Wextra, which turn on most of the warnings of GCC. For this program they find three of the four bugs.

$ gcc -std=c89 -pedantic -Wall -Wextra -o buggy buggy.c
buggy.c: In function ‘sign’:
buggy.c:16:9: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
   16 |     if (x = 0)
      |         ^
buggy.c: In function ‘main’:
buggy.c:28:14: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=]
   28 |     printf("%d\n", big);
      |             ~^     ~~~
      |              |     |
      |              int   long int
      |             %ld
buggy.c: In function ‘sign’:
buggy.c:20:1: warning: control reaches end of non-void function [-Wreturn-type]
   20 | }
      | ^

-Wparentheses reports the assignment in the condition. When an assignment is really meant there, an extra pair of parentheses says so, as in while ((c = getchar()) != EOF). -Wformat compares the conversions of printf with the arguments, and -Wreturn-type finds the path through sign that returns no value. The uninitialized n is not reported.

Warnings from the optimizer

To know that n is used before it is set, the compiler must follow the flow of values through the function. GCC does this when it optimizes, so some warnings appear only with an option such as -O2.

$ gcc -std=c89 -pedantic -Wall -Wextra -O2 -o buggy buggy.c
buggy.c: In function ‘sign’:
buggy.c:16:9: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
   16 |     if (x = 0)
      |         ^
buggy.c: In function ‘main’:
buggy.c:28:14: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=]
   28 |     printf("%d\n", big);
      |             ~^     ~~~
      |              |     |
      |              int   long int
      |             %ld
buggy.c: In function ‘sign’:
buggy.c:20:1: warning: control reaches end of non-void function [-Wreturn-type]
   20 | }
      | ^
buggy.c: In function ‘count’:
buggy.c:6:9: warning: ‘n’ may be used uninitialized [-Wmaybe-uninitialized]
    6 |     int n;
      |         ^
buggy.c: In function ‘main’:
buggy.c:6:9: warning: ‘n’ is used uninitialized [-Wuninitialized]

Now all four bugs are reported. Compiling once with -O2 is worth it even when the program is later debugged without optimization.

lint on the PDP-11

The compiler of the PDP-11 was kept small and fast, and it warns about almost nothing. The checks were left to a separate program, lint, written by Stephen Johnson and shipped with V7 UNIX. lint reads C source like a compiler, but instead of code it produces complaints.

$ lint buggy.c
"buggy.c", line 9: warning: n may be used before set
"buggy.c", line 20: warning: function sign has return(e); and return;
$ cc buggy.c
$ a.out
2304 102
1

lint finds the uninitialized n and the function that returns a value on one path and none on another. It does not look into the format strings of printf, and it accepts the assignment in the condition. The compiler says nothing, and the program prints three wrong numbers: n starts with whatever was on the stack, sign returns whatever was left in the register, and %d prints only the high word of the long, which is 1.

Checking calls across files

The most valuable check of lint compares the calls of a function with its definition, even when they are in different files. The compiler sees one file at a time and cannot do that.

main.c
#include <stdio.h>

double mean();

int main()
{
    static int v[] = { 4, 8, 15, 16, 23 };

    printf("%g\n", mean(v, 5));
    printf("%g\n", mean(v));
    return 0;
}

The second call of mean forgets the number of elements.

stats.c
double mean(v, n)
int v[];
int n;
{
    int i;
    double sum;

    sum = 0.0;
    for (i = 0; i < n; i++)
        sum += v[i];
    return sum / n;
}

mean reads n whether it was passed or not. GCC compiles both files without a warning, because main.c declares mean without its parameters. The first call prints the mean; the second takes a garbage number of elements and runs off the end of memory.

$ gcc -std=c89 -pedantic -Wall -Wextra -o avg main.c stats.c
$ ./avg
13.2
Segmentation fault (core dumped)

On the PDP-11, lint gets both files at once and reports that mean is called with a different number of arguments than it is defined with, naming the line of the definition and of the call. Without the check, the program divides by a garbage n, and the PDP-11 stops it with a floating-point exception.

$ lint main.c stats.c
mean: variable # of args.	"stats.c"(4)  ::  "main.c"(10)
$ cc main.c stats.c
main.c:
stats.c:
$ a.out
13.2
Floating exception - core dumped

A crash in gdb

When a program crashes, a debugger shows where. gdb runs the program, stops it at the fault, and shows the calls that led there. It needs the names of the variables and the lines of the source, which the compiler adds with -g.

crash.c
#include <stdio.h>

int total(v, n)
int *v;
int n;
{
    int sum;

    sum = 0;
    while (n-- > 0)
        sum += *v++;
    return sum;
}

int main()
{
    int *p;

    p = (int *) 0120000;
    printf("%d\n", total(p, 10));
    return 0;
}

main passes total an address where the program has no memory. The program dies with a segmentation fault and gives no hint where. gdb in batch mode runs it, prints the backtrace with bt, and prints the variable n.

$ gcc -std=c89 -pedantic -Wall -Wextra -g -o crash crash.c
$ ./crash
Segmentation fault (core dumped)
$ gdb -q -batch -ex run -ex bt -ex 'print n' ./crash
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Program received signal SIGSEGV, Segmentation fault.
total (v=0xa004, n=9) at crash.c:11
11	        sum += *v++;
#0  total (v=0xa004, n=9) at crash.c:11
#1  0x0000000000401183 in main () at crash.c:20
$1 = 9

The fault happened in total, on line 11, called from line 20 of main. The arguments are shown with their current values: n has already been decremented to 9, and v has already been incremented past 0xa000, the address it could not read. In octal, 0xa000 is 0120000, the address in the program.

A core file in adb

V7 UNIX has no gdb. When a program dies there, the system writes its memory to a file called core, and the debugger adb reads the program and the core file. Its command $c prints the stack of calls, like bt.

$ cc crash.c
$ a.out
Memory fault - core dumped
$ echo '$c' | adb a.out core
~total(0120000,011)
~main(01,0177714)

The shell reports the memory fault and the core file. adb knows no source lines; it shows the functions with the argument words as they are on the stack, in octal. total was called with the address 0120000, and its n has counted down to 011, nine. The C names have a leading ~ here. adb works at the level of the machine: it also prints registers and disassembles instructions.

Null pointers

The null pointer points to no object, and reading through it is an error. Whether the error is caught depends on the machine.

nullread.c
#include <stdio.h>

int main()
{
    int *p;

    p = 0;
    printf("at address 0: %o\n", *p);
    return 0;
}

On Linux, the first page of memory is never mapped, so the read faults at once, and the shell reports it.

$ gcc -std=c89 -pedantic -Wall -Wextra -o nullread nullread.c
$ ./nullread
Segmentation fault (core dumped)
$ echo $?
139

On the PDP-11, address 0 belongs to the program: it holds the first instruction of its code. The read succeeds and prints that instruction, and the program goes on with a wrong value. A program that worked on the PDP-11 could therefore read through null pointers for years, and fail only when it was moved to another machine.

$ cc nullread.c
$ a.out
at address 0: 170011

Knowing the machine

Many bugs come from assumptions about the machine: the size of an int, whether char is signed, how negative numbers are divided and shifted. A short program can print the facts for the machine at hand.

machine.c
#include <stdio.h>

int main()
{
    char c;
    int i, bits;
    unsigned u;

    printf("char %d, short %d, int %d, long %d, pointer %d\n",
        (int) sizeof(char), (int) sizeof(short), (int) sizeof(int),
        (int) sizeof(long), (int) sizeof(char *));
    for (bits = 0, u = 1; u != 0; u <<= 1)
        bits++;
    printf("bits in an int: %d\n", bits);
    i = 0377;
    c = i;
    printf("char 0377 is %d: %s\n", c, c < 0 ? "signed" : "unsigned");
    i = -7;
    printf("-7 / 2 = %d, -7 %% 2 = %d, -7 >> 1 = %d\n", i / 2, i % 2, i >> 1);
    return 0;
}

The program prints the sizes of the types, counts the bits of an unsigned by shifting a 1 until it falls off, stores the bit pattern 0377 in a char, and divides and shifts -7. On x86-64, an int has 32 bits, and a long and a pointer have 64.

$ gcc -std=c89 -pedantic -Wall -Wextra -o machine machine.c
$ ./machine
char 1, short 2, int 4, long 8, pointer 8
bits in an int: 32
char 0377 is -1: signed
-7 / 2 = -3, -7 % 2 = -1, -7 >> 1 = -4

On the PDP-11, an int and a pointer have 16 bits and a long 32. A program that stores a pointer in an int or a long in an int works on one machine and not on the other. The char, the division, and the shift behave the same on both machines, but the language leaves all three to the machine.

$ cc machine.c
$ a.out
char 1, short 2, int 2, long 4, pointer 2
bits in an int: 16
char 0377 is -1: signed
-7 / 2 = -3, -7 % 2 = -1, -7 >> 1 = -4

Debugging output

The oldest debugging tool is a printf in the right place. To keep such lines in the program without printing them all the time, they are put into a macro that disappears unless the program is compiled with DEBUG defined. A K&R macro has a fixed number of arguments, so the arguments of printf are passed as one, in double parentheses.

trace.c
#include <stdio.h>

#ifdef DEBUG
#define DPRINT(args) printf args
#else
#define DPRINT(args)
#endif

int gcd(a, b)
int a, b;
{
    int t;

    while (b != 0) {
        DPRINT(("gcd: a = %d, b = %d\n", a, b));
        t = a % b;
        a = b;
        b = t;
    }
    return a;
}

int main()
{
    printf("%d\n", gcd(1071, 462));
    return 0;
}

When DEBUG is defined, DPRINT(("...", a, b)) becomes printf ("...", a, b): the inner parentheses become the argument list. Otherwise it becomes nothing, and only the semicolon remains, an empty statement. The -D option of the compiler defines the macro from the command line, without changing the source.

$ gcc -std=c89 -pedantic -Wall -Wextra -o trace trace.c
$ ./trace
21
$ gcc -std=c89 -pedantic -Wall -Wextra -DDEBUG -o trace trace.c
$ ./trace
gcd: a = 1071, b = 462
gcd: a = 462, b = 147
gcd: a = 147, b = 21
21

Source

GCC: Options to Request or Suppress Warnings

Debugging with GDB

S. C. Johnson: Lint, a C Program Checker

In this article we have debugged K&R C programs: bugs that compile silently, the warnings of GCC with and without optimization, lint on the PDP-11 for single files and across files, crashes in gdb and core files in adb, null pointers on two machines, a program that prints the facts of the machine, and debugging output with a macro. The porting article shows how prototypes let the compiler itself check calls.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all K&R C tutorials.