简体   繁体   English

使用向量的C ++程序中的分段错误

[英]Segmentation fault in c++ program using vector

I received a segfault when running my code. 运行我的代码时出现段错误。 The code contains a for loop and segmentation fault doesn't appear when I run the program for smaller iterations. 该代码包含一个for循环,当我为较小的迭代运行该程序时,不会出现分段错误。 It appears when I run the code for the larger loop. 当我为较大的循环运行代码时,它就会出现。 I used a debugger to check where doe the problem occurs: 我使用调试器来检查在哪里发生问题:

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)

What does it mean? 这是什么意思? Does anyone know? 有人知道吗? The code error is related to this part of the code: 代码错误与代码的这一部分有关:

  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);
                }

Because value of box_new is out of bound, that is, it may be larger than or equals to the size of box_particles or less than 0. Then corruption occur and segfault. 因为box_new值超出范围,也就是说,它可能大于或等于box_particles的大小或小于0。然后会发生损坏并发生段错误。

Please make sure box_new is in the range [0, box_particles.size()) . 请确保box_new[0, box_particles.size())范围内。 Note that this range may change at each iteration. 请注意,此范围可能会在每次迭代时更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM