views:

236

answers:

3

Hi All

I get the error "list iterator not dereferencable" when using the following code:

bool done = false;
while (!_list_of_messages.empty() && !done) {
    // request the next message to create a frame
    // DEBUG ERROR WHEN NEXT LINE IS EXECUTED:
    Counted_message_reader reader = *(_list_of_messages.begin());
    if (reader.has_more_data()) {
        _list_of_frames.push_back(new Dlp_data_frame(reader, _send_compressed_frames));
        done = true;
    } else {
        _list_of_messages.pop_front();
    }
}

(The line beginning with "Counted_message_reader..." is the one giving the problem)

Note that the error doesn't always occur but seemingly at random times (usually when there's lots of buffered data).

_list_of_messages is declared as follows:

std::list<Counted_message_reader> _list_of_messages;

In the surrounding code we could do pop_front, push_front and size, empty or end checks on _list_of_messages but no erase calls.

I've studied the STL documentation and can't see any glaring problems. Is there something wrong with the above code or do I have a memory leak somewhere?

Thanks! Appreciated!

A: 

For a list, iterators are invalidated when the element of the list that it refers to is erased. That's probably what happens, but I don't see it in your sample code. Wild pointer somewhere ? (not sure, I may be blind after of too much coding).

kriss
I've specifically checked for the "erase" invalidation but don't see it either. No pointers, we do the same deference elsewhere but that's only used locally
Roderick
pop_front also does erase, but as you check it should happen in another thread to have any effect (basicallt what Adrian suggests).
kriss
+1  A: 

This assertion usually indicates some sort of memory corruption bug, such as when you've been manipulating a list from multiple threads or you've overwritten memory that stores the 'bookkeeping' for the list.

Nick Meyer
I suspect overwritten memory but that's not what I want to hear - so I'm hoping for other problems / suggestions :)
Roderick
+1  A: 

Could you have a race-condition?

If the list were empty, then I'd expect a problem when trying to dereference begin(), but you check for empty. Do you have another thread adding or removing items from list in parallel?

Your code snippets works for me on VS 2008 (assuming I typedef Counted_message_reader to int).

Adrian McCarthy
hi Adrian, I don't have other threads accessing the code.Counted_message_reader is a class but that shouldn't matter for this example. The code runs fine for me in general as well - this error seems to be 'random' :-/
Roderick