Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Using GCC Compiler on Code::Blocks, I get an error:

Segmentation fault (core dumped)

Process returned 139 (0x8B)
...

After entering the input asked. Here's my test program:

#include <iostream>
#include <string>

using namespace std;

string getInput(string &input, string prompt)
{
    cout << prompt;
    getline(cin, input);
}

int main()
{
    string input;
    getInput(input, "What's your name?\n>");
    cout << "Hello " << input << "!" << endl;
    return 0;
}

What am I doing wrong, is the reference parameter being used incorrectly?

share|improve this question

3 Answers 3

up vote 7 down vote accepted

The function getInput is declared returning a string but has no return statement which is undefined behavior. If you change the declaration like so:

void getInput(string &input, string prompt)

The segmentation fault should go away. Having warnings turned on would have helped you find this problem, using gcc -W -Wall -pedantic I receive the following warning with your original code:

warning: no return statement in function returning non-void [-Wreturn-type]
share|improve this answer
    
Silly me... It used to return a string, then I changed it to use an out parameter and forgot to change the return value... Thanks, it's hard to see my own mistakes! :) –  Skamah One May 30 '13 at 16:10
    
+1 for the warning recommendation. (BTW, "-W -Wall" is somewhat "deprecated style", nowadays better use "-Wall -Wextra", I find) –  gx_ May 30 '13 at 16:20

The function getInput says that it returns a string, which the calling code attempts to copy. But there is no return in your getInput function. Since copying a return value that wasn't actually returned is undefined behaviour "anything" could happen at this point - in this case, it would appear that a segfault is the result.

Since you are using input as a reference, there is no need to return a string. Just change the function prototype to void.

If you enable warnings when compiling, you will see this sort of error more easily.

share|improve this answer
 string getInput(string &input, string prompt)
 {
    cout << prompt;
    getline(cin, input);
 }  

You declared that the function returns string type, but you did not have return statement in the function. It will result in undefined behavior when the flow reaches the end of that function.

Try:

 void getInput(string &input, string prompt)
 {
    cout << prompt;
    getline(cin, input);
 }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.