c++ - std::string::size() const () 中的段错误?

标签 c++ gdb

我正在编写一个程序,告诉用户输入一个随机字符串,然后打印出所有重复项以及每个重复项的次数。我通过 gdb 运行它,这是输出:

程序如下:

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


运行 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) 


这个输出是什么意思?我该如何解决这个段错误?

最佳答案

一些错误:

if (sentence[i] == sentence[i+1]) {

您的循环允许 i 为 size()-1 - 所以你读的是 vector 句末尾的内容。

while (i != sentence.size()) {
    while (j != sentence.size()) {
     ...
     ++j;
   }
   ++i;
}

j 永远不会重置 - 外循环的下一次迭代将从 sentence.size() 开始- 你可能不想要那样。

你应该用 std::map<std::string, int> 来解决这个问题:

std::map<std::string, int> words;
while (cin >> word) {
    if (word == "ctrlz") {
         break;
    }
    words[word] += 1;
}
for (std::map<std::string>::const_iterator it = words.begin(); it != words.end(); ++it) { 
     if (it->second > 1) {
         cout << it->second << " copies of " << it->first << endl;
     }
}

关于c++ - std::string::size() const () 中的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5306349/

相关文章:

c - 负载很大才出现的bug怎么调试?

c++ - 在非常大的文件中查找最常见的三项序列

c++ - 获取特定距离的键值对数组中第二大的数字

C++:状态和控制模式

c - 共享对象的观察点

linux - 如何将多个输入从文件重定向到正在 gdb 中调试的二进制文件?

c# - 从 C# 调用托管 C++ 时出现编译错误

c++ - 有没有办法使用winapi打开蓝牙?

c++ - 在 C++ 的 fstream 上使用 gdb

c - GDB:将参数转储到特定函数的所有调用