I was writing a program that tell the user to input a random string, and then print out all the duplicates and the number of time each of them repeats. I was running it through gdb and this is the output:
Here is the program:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
//Read a string word by word and put into a vector
//loop through the vector:
// If there are two words duplicate:
// loop through another vector (used to store duplicate word)
// compare if these two words are the same as the duplicate word stored
// If the same: ++count[i]
// If not: push_back(count) ; ++count[i]
string word;
vector<string> sentence;
vector<string> duplicate;
vector<int> times;
int count = 1;
while (cin >> word) {
if (word == "ctrlz") {
break;
}
sentence.push_back(word);
}
vector<string>::size_type i = 0;
vector<string>::size_type j = 0;
while (i != sentence.size()) {
if (sentence[i] == sentence[i+1]) {
while (j != sentence.size()) {
if (duplicate.size() == 0) {
duplicate.push_back(sentence[i]);
times.push_back(count);
++times[0];
}
else {
if (sentence[i] != duplicate[j]) {
duplicate.push_back(sentence[i]);
times.push_back(count);
++times[j+1];
}
else {
++times[j];
}
}
++j;
}
}
++i;
}
while (i != duplicate.size()) {
cout << duplicate[i] << ' ';
++i;
}
return 0;
}
I got this after running gdb:
(gdb) run
Starting program: /home/phongcao/C++/6.12
phong phong phong phong phong phong
ctrlz
Program received signal SIGSEGV, Segmentation fault.
0x001c58d9 in std::string::size() const () from /usr/lib/libstdc++.so.6
(gdb)
What does this output mean? How can I fix this segmentation fault?
Some bugs:
Your loop permits i to be
size()-1– So you’re reading one past the end of the vector sentence.j is never reset – next iteration of the outer loop it’ll start at
sentence.size()– You likely don’t want that.You should solve this with a
std::map<std::string, int>: