tags:

views:

321

answers:

4

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--);
        }
}
+5  A: 

It might be the "numTimes--" that is causing the infinite recursion. The postfix -- will decrement the value within the -- method, but will return the original value of the variable.

Try changing it to --numTimes.

Andy White
+31  A: 

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.

Jesse Rusak
+1 for noting a stack overflow AND suggesting using x-1 instead of x--.
strager
+3  A: 

You are incrementing numTimes after you pass it to Recurse() so you are blowing the stack by continuously recursing into Recurse with the value 10 and never outputting anything to cout.

Arnold Spence
Hey, a stack overflow on stackoverflow :)
Arnold Spence
+3  A: 

Heya!

Firstly, you want to use

#include <iostream>

Without the .h

Now for the program:

#include <iostream>
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 << " ";
        return Recurse(--numTimes);
    }
}

You need to apply the - 1 before evaluation.

Steve Willard