【问题标题】:Segmentation Fault from a While Loop C++来自 While 循环 C++ 的分段错误
【发布时间】:2022-01-22 12:48:35
【问题描述】:

我正在尝试从地图内部进行搜索,将所有相关的子代和后代推入堆栈。 mined是之前声明的json对象。

    if ( !mined[source].empty() ) {
        std::vector<std::string> minedDataVec = mined[source];
        while ( !minedDataVec.empty() ) {
            for (std::string s: minedDataVec) {
                stack.push(s);
                if ( !mined[s].empty() ) {
                    std::vector<std::string> minedDataVec = mined[s];
                } else {
                    minedDataVec.clear();
                }
            }
        }
    }

但是,我遇到了一个分段错误,我很确定这与这段代码中的 while 循环有关。删除 while 循环是可行的,但这意味着每次我想在地图中进行更深入的搜索时,我都必须手动添加更多代码。

【问题讨论】:

  • std::vector&lt;std::string&gt; minedDataVec = mined[s]; -- 您在if 语句中在这里声明了一个局部变量,它与您在其他地方声明的mindDataVec 无关。另外,您是否知道如果条目不存在,地图的operator [] 会插入一个空白条目?
  • 您可能不想更改在该循环中循环的容器的大小。在您的 for 循环中,您循环遍历 minedDataVec 中的每个 s。最终,您可能会运行minedDataVec.clear(),这很可能会导致 for each 循环增加一个无效的迭代器或索引到它不再存在的minedDataVec。此外,当您编写std::vector&lt;std::string&gt; minedDataVec = mined[s]; 时,您定义的变量仅存在于 if 语句的范围内,并且从不使用它。

标签: c++ while-loop segmentation-fault


【解决方案1】:

首先,if 块中声明的名为 minedDataVec 的向量似乎毫无意义...

至于分段错误,可能是因为minedDataVec.clear()使所有引用包含元素的引用、指针或迭代器无效。”(source)。

range-for 循环 for (std::string s: minedDataVec) 有一个到 minedDataVec 的隐式迭代器,它可能会变得无效并导致无效读取访问导致分段错误。

【讨论】:

  • 我应该如何使if 块内的minedDataVec 有意义?当我尝试minedDataVec = mined[s]; 时,我收到一条错误消息use of overloaded operator '=' is ambiguous
  • 为什么需要在if 块中再次设置minedDataVec?也许你需要另一个数组来存储所有元素,使用vector.push_back
猜你喜欢
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2014-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多