I’m writing a piece of code meant to reverse strings using recursion. I believe my method is correct, but I keep getting a segmentation fault and I’m not sure where it’s coming from. All my research indicates that it means I’m doing “something strange with memory”. I’m new enough at this that these kinds of errors are still baffling, so any help here would be much appreciated. Here’s my code:
#include <iostream>
#include <string>
using namespace std;
class Palindrome
{
int front;
int back;
public:
Palindrome();
string reverse(string word)
{
int len = word.length()-1;
if (back == 0) {
back = len;
}
if (front >= back)
return word;
else{
char first = word[front];
char last = word[back];
word[front] = last;
word[back] = first;
front += 1;
back -= 1;
reverse(word);
}
}
};
Palindrome::Palindrome(){
front = 0;
back = 0;
}
I tried your code and got an “access violation” too, even with only one call. Beside the initialization issue described in other answers and comments, what is causing your seg fault is the missing “return” before your recursive call to “reverse”. You need to write
return reverse(word);In Visual Studio, your original code gives this: warning C4715: ‘Palindrome::reverse’ : not all control paths return a value.
See this question for more details.
Here’s a version of reverse() with both fixes: