Why am I having this error message from g++?

2019-08-11 10:05发布

问题:

Below is my code. It compiles fine in g++, but there is always this running time error: Segmentation fault (core dumped)

Where am I wrong?

#include<iostream>
#include<string>

using namespace std;

void sort_string(string x){
    for (int i=0;x.size();i++){
                    for(int j=i;x.size();j++){
                            char temp = x[i];
                            if (temp > x[j]){
                                    x[j]=temp;
                                    x[i]=x[j];
                            }
                    }
    }
}


int main(){
    string words;
    cin >> words;

    while (words != " "){
            cout << words << " ";
            sort_string(words);
            cout << words << endl;
    }

}

回答1:

You are looping beyond the bounds of the string. You need this:

for (int i=0; i<x.size(); i++){ ... }

Similarly for the inner loop. x.size() will evaluate to true unless the string is empty. Since this is the loop termination condition, the loops will run forever for non-empty strings.



回答2:

Your condition makes no sense. That x.size() part in your for loops should be a condition to terminate your loops. This will always return some non-zero value unless your string is 0 which means that your code executes infinitely. Then, j always increments and you go out of bounds. You need to supply a valid condition such as i < x.size() and j < x.size().



回答3:

The conditions of your for are wrong. Replace

for (int i=0;x.size();i++){
    for(int j=i;x.size();j++){

with

for (int i=0; i<x.size();i++){
    for(int j=i; j<x.size();j++){

otherwhise you will loop endlessy



标签: c++ g++ iostream