简体   繁体   中英

std::deque memory corruption when using iterator to erase elements

My code occasionally crashes because of the following

//queue is a std::shared_ptr<std::deque<Something> >
//I can guarantee that queue will never be empty.
std::deque<Something>::iterator it = queue->end();
it--;
queue->erase(it);

Not always, but sometimes. It happens mostly after I added something to the front then try to delete the back.

If I change it to

queue->pop_back();

At lease haven't seen it crashing for a long time.

But can anyone enlighten me why the former code will crash? I guess it is something related to the fact that resizing may invalidate all iterators. But what I did was -- not ++ .

Can anyone please explain to me why?

//-----------------------

// Update

//-----------------------

My understanding is it is just a pointer. There is no insertion, between getting it and using it .

The only operation is it-- . But since it-- is a pointer moving. We always do

for(it = xxx.begin(); it!=xxx.end(); ++it)
{
    ...
}

It works fine. Or is the following illegal?

for(it=xxx.end();it!=xxx.begin();--it){...}

What I don't understand is why a pointer moving in the valid range, will cause memory corruption.

Because after -- , it points the exact element I want, there is no way to re-get this pointer unless I just use ( xxx.end()-1 ) instead.

Thanks

If your queue is not empty - everything is fine with your code.

Your statement about reverse iterating

for(it=xxx.end();it!=xxx.begin();--it){...}

can be illegal in case if you will manipulate iterator in loop body. Dereferencing xxx.end () can lead to segmentation fault. In this case it's better to use reverse iterators:

for(it=xxx.rbegin();it!=xxx.rend();++it){...}

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