【问题标题】:C++ std::vector<std::string> iterator segfaultsC++ std::vector<std::string> 迭代器段错误
【发布时间】:2014-11-08 11:33:18
【问题描述】:

我在遍历文件名向量时遇到了这个段错误。 std::vector 由另一个以非常混乱的代码读取 csv 的函数填充。因此,我将其范围缩小到导致问题的以下代码。

在产生具有 4 个项目的向量的第一个(有时稍后)项目后向量段错误的迭代器。按第 5 项可解决问题。奇怪的?矢量迭代器工作正常。

#include <iostream>
#include <vector>

using namespace std;

std::vector<int> popbar() {
    // populate vector of integers
    //
    std::vector<int> bar;

    for(int i = 1; i < 6; i++)
        bar.push_back(i);

    return bar;
}

std::vector<std::string> popxar() {
    // populate vector of strings
    //
    std::vector<std::string> xar;

    xar.push_back("one");
    xar.push_back("two");
    xar.push_back("three");
    xar.push_back("four");
    // this line fixes segfault
    //xar.push_back("five");

    return xar;
}

void foo () {
    // yield next vector item
    //
    //auto bar = popbar();
    auto bar = popxar();

    //static auto itx = bar.begin();
    static vector<string>::iterator itx = bar.begin();

    if (itx == bar.end()) {
        cout << "end of line" << endl;
        itx = bar.begin();
    }

    cout << *itx++ << endl;
}

int main() {
    for(int i = 0; i < 11; i++) {
        foo();
    }
}

预期的输出是

one
two
three
four
end of line
one
two
three
four
end of line
one
two
three

我得到的输出是

one
Segmentation fault

也见过

one
two
three
Segmentation fault

和

one
three
three
���1������������1one1fourSegmentation fault

如果这使它更有趣。可以?也请考虑这个向量。

【问题讨论】:

  • 好像是内存损坏了,能否开启gflags并通过调试器运行
  • 只是好奇,您首先将vector&lt;string&gt;::iterator 设为foo() 函数中的静态变量的原因是什么?
  • 我真的很喜欢最后一组输出。非常完美地说明了未定义的行为。

标签: c++ string c++11 vector iterator


【解决方案1】:

您为局部变量定义了一个静态迭代器。你预计会发生什么?

当foo 返回时,本地向量xar 将被销毁,这会使您的所有迭代器无效。重新输入foo 会创建一个全新的向量,然后您尝试使用无效的迭代器。未定义的行为随之而来。

【讨论】:

  • 好的,我错过了,谢谢。但是,为什么它始终如一地为定义的 vector 工作!?也适用于具有五个项目的向量。真的很困惑。
  • @user1480788 - But then how come it is working for vector&lt;int&gt; as defined, consistently!? 也表示为 `为什么当我做这个明显的非法构造时,我的程序可以工作?" 当你在 C++ 中做这样的事情时,行为是未定义。“未定义”意味着任何事情都可能发生,包括工作、失败、今天工作明天失败、在您的计算机上工作但在另一台计算机上失败等。
【解决方案2】:

这是因为您有一个指向非静态局部变量的 static 迭代器。当foo 函数返回时,bar 被破坏。这导致undefined behavior。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 2012-05-07
    相关资源
    最近更新 更多