2

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?

Kaiden Prince
  • 472
  • 3
  • 18

2 Answers2

2

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.

rts1
  • 1,416
  • 13
  • 15
  • 2
    It's still going to crash when it runs out of memory-- – antlersoft Oct 07 '15 at 17:10
  • 1
    Yes, but he may make it far enough for his purposes. Another solution would to cache/memoize small values so it doesn't ave to do as much recursion. – rts1 Oct 07 '15 at 17:11
1

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055