I have created a very simple program that uses recursion. I'm using the g++ compiler. I can compile it, but when I try to run it I get an error message that says SEGMENTATION FAULT. Here's my code:
#include <iostream.h>
using namespace std;
int Recurse(int);
int main(int argc, char *argv[])
{
Recurse(10);
cout << endl;
}
int Recurse(int numTimes)
{
if (numTimes == 0)
return 0;
else
{
cout << numTimes << " ";
Recurse(numTimes--);
}
}
In your recursive call, you're using the postfix --
(numTimes--
), rather than the prefix version (--numTimes
). As a result, the value of numTimes
is decremented after the recursive call. This means that Recurse is called with 10 infinitely. Use the prefix version (which will decrement it before the call), or just pass numTimes-1
(since the numTimes value doesn't need to be modified).
The reason you're seeing a segfault is that your stack overflows into protected memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With