I'm perplexed by a crash I'm getting with the following code:
#include <stdio.h>
FILE *ofp;
const char *mode = "r";
char outputFilename[] = "data.txt";
unsigned long long int chaser(unsigned long long int x) {
if (x == 0) {
printf("x was 0 at some point \n",x);
fprintf(ofp,"x was 0 at some point \n",x);
return 0;
}
else {
fprintf(ofp,"initially x in else is %lld\n",x);
x = chaser(x-1) + 1; // recursion overflow?
fprintf(ofp,"after, x in else is is %lld\n",x);
}
return x;
}
int main() {
ofp = fopen(outputFilename, "w");
if (ofp == NULL) {
fprintf(stderr, "Can't open output file %s!\n",outputFilename);
return(1);
}
unsigned long long int i = 65096; // 65095 and above fail
unsigned long long int n;
n = chaser(i);
printf("finished %lld\n",n);
fclose(ofp);
return 0;
}
If 'i' is less than 65095 then everything prints, and everything works fine.
If 'i' is set to 65095 or greater, then it prints nothing to the console, issues a crash message on win8, and simply exits on XP. In the output file it gets down to:
initially x in else is 29
initially
It does not finish the sentence after 'initially' in the last line of the file.
Apparently the crash is a segfault. Could this be a buffer overflow of some sort? How can I get it to run into the hundreds of millions?
Thank you for your time.