简体   繁体   中英

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. 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.

Please make sure box_new is in the range [0, box_particles.size()) . Note that this range may change at each iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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