Search code examples
c++algorithmrecursionpermutationheaps-algorithm

Heap's Algorithm in C++ segmentation fault


I've been working on implementing a recursive version of heap's algorithm. Here is the link to the pseudocode: http://en.wikipedia.org/wiki/Heap%27s_algorithm

Everything has been going fine until I get to the recursive part. I know I haven't put in swapping elements yet but I haven't gotten that far. The run fails without showing an error until I use the gcc debugger which tells me that there has been a segmentation fault. Here is my code:

#include <string>
#include <iostream>
using namespace std;

string* permute(int n, string array[2]){
    if (n==1){
        return array;
    }
    else{
        for(int c=1; c<=n;c++){
            permute(n--,array);
        }
    }
}

int main() {
    string array[2]={"a","b"};
    permute(2,array);
    return 0;
}

Solution

  • Let aside the fact that the entire implementation seems wrong, the direct reason for the runtime exception that you're experiencing is your recursive call to permute(2,array), which eventually leads to a stack overflow. This happens because you are calling it with n-- instead of --n (or more precisely, n-1).