【发布时间】: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 < 5; i++)你怎么知道至少有 5 个项目?为什么不通过循环到min(5, pointerVector.size());来确定? -
@RaphaelSeize 不,您显示的代码不会这样做。无论如何,您循环5次。您将
5硬编码到循环条件中。只要你对一个少于 5 个元素的向量执行此操作:PointTwoD p1 = pointVector[i];你就死定了。
标签: c++ pointers segmentation-fault fault