Need help with error program gives segment fault core

Program keeps giving me a segemntation fault error


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

string reverse(string word, int size, string newWord)
{
if(size == 1)
{
return newWord;
}
else
{
reverse(word, size-1, newWord+ word.at(size-1));
}
}

int main()
{
string choice, reversal = " ";
cout << "Enter a word: ";
cin >> choice;

int length = choice.length();
reverse(choice, length, reversal);

return 0;
}
Can't reproduce your segmentation fault error. You need to be more precise
Here I changed a few things but it still does not work I ran it on linux compiled with
g++ reverse.cpp -o reverse
./reverse

I get this error
*** Error in `./reverse': free(): invalid pointer: 0x00007fff89c58298 ***
Aborted core dumped

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

string reverse(string word, int size, string newWord)
{
if(size == 1)
{
return newWord;
}
else
{
newWord += word.at(size-1);
reverse(word, size-1, newWord);
}
}

int main()
{
string choice, reversal = "";
cout << "Enter a word: ";
cin >> choice;

int length = choice.length();
cout << reverse(choice, length, reversal) << endl;


return 0;
}
1
2
3
4
5
6
7
8
9
10
#include <string>

std::string reverse( std::string str )
{
    if( str.size() < 2U ) return str ;

    else return reverse( str.substr(1) ) + str.front() ;
    // http://www.cplusplus.com/reference/string/string/substr/
    // http://www.cplusplus.com/reference/string/string/front/
}
What is 2U can you explain what you did because I am lost
The suffix U specifies that it is the unsigned integer 2.
https://en.wikipedia.org/wiki/Integer_literal#Affixes

if( str.size() < 2 ) return str ; // this would also wok
Hi,

Just a couple of minor things to add:

Don't have using namespace std;, it can cause name clashes. Refer to things in std by prefixing them with std::, like JLBorges has done with std::string. Also std::cout , std::cin , std::endl, std::vector etc.

Also compile with these switches as a suggested minimum:

g++ -std=c++11 -Wall -Wextra -pedantic reverse.cpp -o reverse

this will give warnings that you may not have otherwise had. It is worth reading through the documentation for gcc, although it is long (there are zillions of options).

Can we ask you to always use code tags? Edit your post, select the code, then press the <> button on the format menu.

Hope you all are enjoying the festive season o<:+D
Topic archived. No new replies allowed.