mashroor
mashroor

Reputation: 51

Why am I getting a 'Segmentation Fault: 11' line in my C++ code?

I'm new to coding in c++ and for a homework assignment I keep getting a Segmentation Fault: 11 and I'm not sure why. I did a little research beforehand and I tried changing all my variable names, with no difference. What should I do to fix this? Below is my code.

#include <iostream>
using namespace std;

string middle(string str);

string middle(string str){
    if(str.length() % 2 == 1){
        cout << str[str.length()/2] << endl;
        return 0;
    }
    else if(str.length() % 2 == 0){
        cout << str[(str.length() + 1)/2];
        cout << str[((str.length() + 1)/2) - 1];
        return 0;
    }
    return 0;
}

int main(){
    string a_word;

    cout << "Enter a word: ";
    cin >> a_word;
    middle(a_word);
}

Upvotes: 3

Views: 971

Answers (2)

Lukas-T
Lukas-T

Reputation: 11340

string middle(string str)

defines a function that will return a std::string, but you do

return 0;

As Kevin correctly found out, this actually compiles. std::string has a constructor that takes only a const char* as parameter, thus it qualifies as implicit conversion constructor and the literal 0 can be parsed as a null pointer literal (doesn't work with other numbers). So the appropriate constructor (number 5) get's called and expects a valid pointer. The reference states that:

The behavior is undefined if [s, s + Traits::length(s)) is not a valid range (for example, if s is a null pointer).

And exactly that's the case, the parameter passed to the constructor is 0, so you get undefined behaviour. A seg fault in your case, an exception in my case.


To solve this, just remove all the return's and change the return type to void since you neither use the returned value, not return any meaningfull value in the first place.

Note that this will still fail for empty strings, you should add a check for this case.

void middle(string str) {
    if(str.empty()) {
        return;
    }

    if (str.length() % 2 == 1) {
        cout << str[str.length()/2] << endl;
    }
    else if (str.length() % 2 == 0) {
        cout << str[(str.length() + 1)/2];
        cout << str[((str.length() + 1)/2) - 1];
    }
}

Upvotes: 3

cgDude
cgDude

Reputation: 93

#include <iostream>
using namespace std;


void middle(string str){
    if(str.length() % 2 == 1){
        cout << str[str.length()/2] << endl;
        return ;
    }
    else if(str.length() % 2 == 0){
        cout << str[(str.length() + 1)/2];
        cout << str[((str.length() + 1)/2) - 1];
        return ;
    }
    return ;
}

int main(){
    string a_word;

    cout << "Enter a word: ";
    cin >> a_word;
    middle(a_word);
}

change your code to this it will work. I have changed return type of function to void instead of string. The segmentation fault occurs because you were returning an integer while return type of function was string.

Upvotes: 3

Related Questions