#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#define max 100000000
int64_t table[max];
int64_t collatz(int64_t a);
int main(int argc,char*argv[])
{
if (argc !=3)
{
printf("ERROR\nUsage: ./collatz {argv1} {argv2}\n");
return 1;
}
int64_t maxlen = 0;
int64_t num1 = atoi(argv[1]);
int64_t num2 = atoi(argv[2]);
if (num1 < 1 || num2 < 1 || num1 > max || num2 > max)
{
printf("%"PRId64"\n",maxlen);
return 2;
}
int64_t i;
for (i=num1;i<=num2;i++)
{
int64_t len = collatz(i);
if (len > maxlen)
{
maxlen = len;
}
}
printf("%" PRId64 "\n", maxlen);
return 0;
}
int64_t collatz(int64_t a)
{
if (a <= max)
{
if(table[a] != 0)
{
return table[a];
}
}
int64_t len = 1;
if (a != 1)
{
if (a%2==0)
len += collatz(a/2);
else
len += collatz(a*3+1);
}
if (a <= max)
{
table[a]=len;
}
return len;
}
When I remove the last if statement in the collatz function I get a segmentation fault. I can't understand this because the array size is 100.000.000 and I never allow a number bigger than that to enter. Also I know a number can exceed the limits inside the function e.g. 99.999.999 but I am pretty sure a number higher than 100.000.000 will never meet the last if statement in the function, but if I remove it somehow I get a segmentation fault.
In the
collatz
function you havetable
as an array of sizemax
. That means the maximum valid index ismax - 1
. Yet, you test thata
is less than or equal tomax
. This permits an out of bounds array access and a segmentation fault is a possible result.