― Edgar Allan Poe, The Purloined Letter
Below, you find a little C project that doesn’t do what it’s supposed to do, namely print the sum of the first 10 prime numbers. The program builds cleanly with gcc and clang; that is, without any warnings even when using -Wextra -Wall -pedantic -ansi as compiler options. It’s well-formed and doesn’t crash.
What’s the root cause of this bug? What’s the output of the program? Here are the files, you can also find them on GitHub:
prime_table.h:
1 2 3 4 5 6 7 8 |
#ifndef PRIME_TABLE_H #define PRIME_TABLE_H const unsigned int PRIME_TABLE[10]; #endif |
prime_table.c:
1 2 3 4 5 6 7 |
#include "prime_table.h" const unsigned int PRIME_TABLE[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, }; |
prime_sum.c:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <stdio.h> #include "prime_table.h" #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0])) int main(void) { unsigned int sum = 0, i; for (i = 0; i < ARRAY_SIZE(PRIME_TABLE); ++i) { sum += PRIME_TABLE[i]; } printf("%u\n", sum); return 0; } |
Makefile:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
CFLAGS := -Wextra -Wall -pedantic -ansi run: prime_sum ./prime_sum prime_sum.o : prime_sum.c prime_table.h prime_table.o : prime_table.c prime_table.h prime_sum : prime_sum.o prime_table.h clean: rm -rf prime_sum *.o |