【问题标题】:Segfault in map地图中的段错误
【发布时间】:2010-08-22 13:08:32
【问题描述】:

我不明白为什么这段代码会因段错误而失败:

#include <cstdlib>
#include <iostream>
#include <map>
#include <string>

using namespace std;

int main(int argc, char** argv) {

    map <string, string> temp;
    map <string, string>::iterator it;

S
字符串文本 = ""; 字符串 thatChange = ""; 字符串 whatChange = "";

    getline (cin, text);


    while (true)
    {
        getline (cin, thatChange);
        if (thatChange == "-1")
            break;

        getline (cin, whatChange);
        temp.insert(pair <string, string> (thatChange, whatChange));
    }

    for (int i = 0; i < temp.size(); i++)
    {
        string thatChange = it->first ; // thatChange
        string whatChange = it->second; // whatChange
        it++;

        int index = text.find(thatChange);
        text.erase(index, thatChange.size());
        text.insert(index, whatChange);
    }

    cout << "text\n"<< text;

    return 0;
}

更新: 调试器说:

No source available for "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string() at 0x7ffff7b75928" 

【问题讨论】:

  • 你使用什么头文件或编译器?我插入了 以及 using namespace std; 并用 gcc 编译,这里没有段错误。
  • 请发布一个完整的编译代码示例,而不仅仅是一个片段。
  • 好吧,它对我来说不会崩溃。你使用的是什么编译器,你传递了什么标志?
  • 我不会崩溃(在 VS2010 上)。请注意,您永远不会更改 whatChange 的值。 whatChange 始终是空字符串。贴出真实代码。
  • @dirkgently:在break;之后改了

标签: c++ map insert std segmentation-fault


【解决方案1】:
string thatChange = it->first ;

这一行调用了 UB。到目前为止,it 从未被初始化过。您应该按如下方式初始化它:

it = tmp.begin();

并遍历地图使用的所有元素:

for (map<string, string>::const_iterator f = temp.begin(), e = temp.end;
     f != e;
     ++f) {
   // ....
}

【讨论】:

    【解决方案2】:

    FWIW 代码 sn-p 编译并在 VS2010 上运行良好,因此如果您遇到错误,问题可能位于其他地方。

    【讨论】:

      猜你喜欢
      • 2020-07-03
      • 2018-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2015-01-09
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多