Kaiden Prince
Kaiden Prince

Reputation: 472

Segmentation fault in a massively recursive function

I have a function that calls itself a near infinite amount of times, but it does have an end. It calculates the mathematical formula (in TeX):

When x<a:

g_{a}(x)=1

When x>=a:

g_{a}(x)=g_{a}(x-1)+g_a(x-a)

Here is my code(c++):

#include <iostream>
#include <math.h>
#include <stdio.h>
#include <cmath>
using namespace std;
double g( double a, double x){
    if (x>=a) return (g(a,x-1)+g(a,x-a));
    else if (x<a) return 1;
    return 0;
}
int main(){cout << g(sqrt(10000019),10000019);}

I call the function with g(sqrt(10000019),10000019); How do I stop the SEGFAULT?

Upvotes: 2

Views: 301

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

I have a function that calls itself a near infinite amount of times, but it does have an end.

Do you have a near infinite amount of stack memory?

If not (the likely scenario), you are going to smash your stack in no time. A segmentation fault is a clear sign of that here.

I'd avoid the recursion altogether.

Upvotes: 1

rts1
rts1

Reputation: 1466

I suspect your seg-fault was from running out of stack space.

You can limit/unlimit how big your stack space is (on Linux at least) using the limit command from tcsh.

 % limit 
cputime      unlimited
filesize     unlimited
datasize     unlimited
stacksize    10240 kbytes
coredumpsize 0 kbytes
memoryuse    unlimited
vmemoryuse   unlimited
descriptors  4096 
memorylocked 64 kbytes
maxproc      1024 

You can then unlimit your stacksize

% unlimit stacksize
% limit

cputime      unlimited
filesize     unlimited
datasize     unlimited
stacksize    unlimited
coredumpsize 0 kbytes
memoryuse    unlimited
vmemoryuse   unlimited
descriptors  4096 
memorylocked 64 kbytes
maxproc      1024 

And give it another try.

Upvotes: 2

Related Questions