【问题标题】:Segmentation fault core dumped vector pointer [closed]分段错误核心转储向量指针[关闭]
【发布时间】:2016-04-20 13:48:52
【问题描述】:
void printTop5()
{
    int counter = 1;
    int x, y;
    float civ;
    cout << "Total no. of records available = " << pointVector.size();
    cout << "Printing top 5 exploration destinations....";
    sort(pointVector.begin(), pointVector.end(), ascendingCiv);
    for (int i = 0; i < 5; i++)
    {
        PointTwoD p1 = pointVector[i];
        x = p1.getX();
        y = p1.getY();
        civ = p1.getCivIndex();
        cout << counter << ")\t";
        if (civ > 0)
        {
            cout << "Civ idx: " << civ << " ; at sector(" << x << "," << y < ")\n";
        }
        else
            cout << "<No records available>";
    }
    }

bool ascendingCiv(const PointTwoD &d1, const PointTwoD &d2)
{
    return d1.getCivIndex() > d2.getCivIndex();
}

当我运行这个函数时,我得到了这个错误,它说分段错误核心转储。任何的想法?听说有内存问题。

【问题讨论】:

  • 当它核心转储时,您可以检查哪一行代码失败了,所以不是您的个人调试器
  • @RaphaelSeize 通过使用您选择的调试器。以GDB 为例。
  • @RaphaelSeize for (int i = 0; i &lt; 5; i++) 你怎么知道至少有 5 个项目?为什么不通过循环到min(5, pointerVector.size()); 来确定?
  • @RaphaelSeize 不,您显示的代码不会这样做。无论如何,您循环5次。您将5 硬编码到循环条件中。只要你对一个少于 5 个元素的向量执行此操作:PointTwoD p1 = pointVector[i]; 你就死定了。

标签: c++ pointers segmentation-fault fault


【解决方案1】:

一个问题是您没有检查您的向量中是否实际上至少有 5 个元素:

for (int i = 0; i < 5; i++)
{
    PointTwoD p1 = pointVector[i];

如果i 超出向量范围,访问pointVector[i] 将调用未定义的行为。

循环条件可以改成如下:

#include <algorithm>
//...
size_t loopEnd = std::min(pointVector.size(), 5);
for (size_t i = 0; i < loopEnd; i++)
{
    PointTwoD p1 = pointVector[i];

循环将增加到向量的大小或 5 个元素,以较小者为准。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-04
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多