我在运行代码时收到段错误。代码包含一个 for 循环,当我运行程序进行较小的迭代时不会出现分段错误。当我为较大的循环运行代码时,它会出现。我使用调试器来检查问题发生的位置:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004062d0 in std::vector<int, std::allocator<int> >::push_back (
this=0x64dc08, __x=@0x7fffffffd180: 32)
at /usr/include/c++/5/bits/stl_vector.h:915
915 if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage)
什么意思?有人知道吗?代码错误与这部分代码有关:
int box_new = getBoxID(x[i],y[i],R0,nbox);
if(bx[i] != box_new)
{
vector<int>::iterator position = std::find(box_particles[bx[i]].begin(), box_particles[bx[i]].end(), i);
if (position != box_particles[bx[i]].end()) // .end() means the element was not found
box_particles[bx[i]].erase(position);
bx[i] = box_new;
box_particles[box_new].push_back(i);
}
因为 box_new
的值是越界的,也就是说,它可能大于或等于 box_particles
的大小或小于 0。然后发生腐败和段错误。
请确保box_new
在[0, box_particles.size())
范围内。请注意,此范围可能会在每次迭代时更改。