Posted on
Hello World might be the most frequently written computer program. For decades,
it’s been the first program many people write, when getting started in a new
programming language.
Surely, this humble starting-point program should be bug free, right?
After all, hello world programs only do one thing. How could there be a bug?
Hello world in C
There are a lot of different ways to write hello world in C. There’s
the Wikipedia version, the hello world in the K&R book, and there’s
even the oldest known C hello world program from 1974.
Here’s another, this one in “ANSI C”:
/* Hello World in C, Ansi-style */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
puts("Hello World!");
return EXIT_SUCCESS;
}
This is the most careful version of the bunch. It uses (void)
to ensure that
main
is a new-style declaration. It uses the EXIT_SUCCESS
macro instead
of just assuming that the platform uses 0 to indicate success, which isn’t
necessary, according to the C standard, but we’re not taking any chances here.
And it uses the appropriate headers to avoid implicitly declaring puts
. This
version attempts to do everything right.
And yet, it still has a bug.
All the versions linked above have a bug.
A bug?
Linux has this fun device file called “/dev/full”, which is like its more
famous cousin “/dev/null”, but when you write to “/dev/full”, instead of
throwing away the data, it fails. It acts like a file on a filesystem that
has just run out of space:
$ echo "Hello World!" > /dev/full
bash: echo: write error: No space left on device
$ echo $?
1
This is a great little tool for testing that programs handle I/O errors
correctly. It’s inconvenient to create actual filesystems with no
space left, or disks that actually fail, but it’s really easy to ask a
program to write its output to “/dev/full” and see what happens.
So let’s test the C example above:
$ gcc hello.c -o hello
$ ./hello > /dev/full
$ echo $?
0
Unlike when we used echo
in the shell above, here, we got no output, and
the exit status was zero. That means the hello
program reported successful
execution. However, it didn’t actually succeed. We can confirm that it
encounters a failure u