Search code examples
c++segmentation-faultdeque

Segmentation faults in deque of user-defined pointers


I have a deque<rect*> rects where rect is a user-defined class. When I try to insert a rect* into it, I get a segmentation fault. gdb traces the problem back to a function called __memmove_sse3() from my calling rects.insert(it,new rect([constructor parameters])); where it is a deque<rect*>::iterator. What could cause this error?

EDIT: here is a snippet of my code:

for(deque<rect*>::iterator it=rects.begin();it!=rects.end();++it)
        {
            rect r=*r1;
            rect r2=*(*it);
            if(!r2.there)
                continue;
            if(r.down>r2.up || r.up<r2.down || r.right<r2.left || r.left>r2.right)
                continue;
            if(r.left>r2.left)
                rects.insert(it,new rect(r2.left,r2.down,r.left,r2.up,r2.color));
            if(r.right<r2.right)
                rects.insert(it,new rect(r.right,r2.down,r2.right,r2.up,r2.color));
            if(r.up<r2.up)
                rects.insert(it,new rect(max(r.left,r2.left),r.up,min(r.right,r2.right),r2.up,r2.color));
            if(r.down>r2.down)
                rects.insert(it,new rect(max(r.left,r2.left),r2.down,min(r.right,r2.right),r.down,r2.color));
            r2.there=false;
        }

Solution

  • The problem is that you're inserting item to std::deque which invalidates the iterator which you're incrementing in the for loop:

    The Standard (draft n3485) says in §23.3.3.4/1 (emphasize mine),

    Effects: An insertion in the middle of the deque invalidates all the iterators and references to elements of the deque. An insertion at either end of the deque invalidates all the iterators to the deque, but has no effect on the validity of references to elements of the deque.