Bug Two Answer

This one really got me for a long time, since the Seg fault was hidden furtively in a huge program, and my debugging printf's kept indicating the fault was happening at all these completely insane places, such as assignments to direct (nonpointer) atomic types or after a function call but before the first line of the function.

Anyway, the problem is buffering. printf is trying to be clever and really only outputing your data every once in a while. So when you say printf, your program is really just appending the printed string to a buffer in memory which it will later actually output to the screen (or file, etc) at its leisure. If you are using print's as a debugging tool, you need to fix this by explicitly flushing the buffer after each debug print. In C++/iostream output, this happens every time you conclude with an endl, or you could just:
cout << flush;
which is the same thing without the newline. In C/stdio.h terms, you should call fflush(). The following modified version of the buggy program always prints a 2 before Seg faulting.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
	void *vp = 0;
	int i;
	srand(time(0));

	while (1) {
		printf("1");
		if ((rand() % 20000) == 3) {
			printf("2");
			fflush(stdout);
			i = *(int *)vp;
		}
		printf("3");
	}

	return 0;
}


Bugs