What is causing segfaults on my compiler? Onlinegdb.com throws a segfault, whereas the built-in compiler for cpp.sh runs my code perfectly fine without any errors ever.
This code basically takes the smallest possible prime factors of a number and outputs them. It runs in cpp.sh but not onlinegdb, and I'm wondering what is causing a segfault there instead of here, and how that all ties in?
#include <iostream>
void getSmallestFactors(int num);
bool checkPrime(int num);
struct twoInts
{
int num1;
int num2;
};
twoInts getGreatestTwo(int nonPrime);
int main()
{
int x;
std::cout << "Enter a positive integer greater than 1." << std::endl;
std::cin >> x;
getSmallestFactors(x);
}
void getSmallestFactors(int num)
{
if(checkPrime(num))
{
std::cout << num << " ";
}
//if false, control turns to splitting into factors.
//Factor splitter finds the greatest factors of a number, then runs getSmallestFactors() for both.
//this checks if those numbers are prime, outputting them if they are, and if not, running getSmallestFactors again,
//which will output them if they are prime or make prime numbers if not.
else
{
twoInts gfactors;
gfactors = getGreatestTwo(num); //gets the greatest two factors. can see if they're prime below.
getSmallestFactors(gfactors.num1);
getSmallestFactors(gfactors.num2);
}
}
twoInts getGreatestTwo(int nonPrime) //4
{
//we can get the greatest factor with nonPrime % i == 0 in a decrementing iterator loop.
//the number we're dealing with / the greatest factor of that number = num2.
twoInts returnTwo;
for(int i = (nonPrime-1); i > 1; i--)
{
if(nonPrime % i == 0 and returnTwo.num1 == 0) //if a factor of the int is found, and the first int hasn't been set.
{
returnTwo.num1 = i;
break;
}
}
returnTwo.num2 = (nonPrime / returnTwo.num1);
return returnTwo;
}
bool checkPrime(int num)
{
for(int i = 2; i < num; i++)
{
if(num % i == 0)
{
returnfalse;
}
}
returntrue;
}
at a glance I don't see anything, so my first gut-guess is to tell you to add a line about the recursive depth into the recursion and see how deep it goes.
then try a simple do-nothing recursive test function on the same compiler and drive it to crash on purpose and see how far it gets. If its similar depth, the answer may be the recursive stack space. It shouldn't happen easily, but that "could" be it.
That code would not compile with Visual Studio...unless you turn off SDL checks and ignore warnings. Your program will do unpredictable things, I'm guessing it would fail checks and keep recursing until it blows the stack...haven't looked too closely at what it is doing.