user1559897
user1559897

Reputation: 1484

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

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;
    }

}

Upvotes: 1

Views: 92

Answers (3)

pinco
pinco

Reputation: 891

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

Upvotes: 0

ApplePie
ApplePie

Reputation: 8942

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().

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227390

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.

Upvotes: 3

Related Questions