Segmentation fault about data type?

Viewed 65

I find out that my code only works with n <= 43429. If n>43429, it causes a segmentation fault. Did I wrong with the data type or anything?

here is my code and debug result: enter image description here

#include<stdio.h>
#include<windows.h>

double recursive(long n);

int main(){
    printf("\nEnter n:");
    long n; scanf("%ld", &n);
    printf("\n%.2lf", recursive(n));
    getch();
    return 0;
}

double recursive(long n){
    if(n<=1) return 1;
    else return (double)1/n + recursive(n-1);
}
1 Answers

Every recursive call requires space on the call stack (often referred to as just "the stack"). The stack has a fixed maximum size. If you use up all of the space in the stack, the program crashes. Your OS and/or your compiler default to making the stack big enough for 43429 recursive calls, but not more.

There is usually a way to request more space for the stack, but not from within the program. On Windows you specify the needed size in the "module .def file". I am not familiar with the IDE you are using, but that should translate to a knob in the project configuration somewhere.

Alternatively, this would be a good time to learn how to convert recursion to iteration. Your program is almost tail recursive so it's an easy case.

I don't know how you managed to get Windows to report this crash using the phrase "Segmentation fault", but that's not important right now.

Related