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

被刻印的时光 ゝ 提交于 2019-12-11 08:34:02

问题


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



来源:https://stackoverflow.com/questions/12887060/why-am-i-having-this-error-message-from-g

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!