C ++ list iterator never reaches end () when repeated

Well, I wrote a program that works great when compiled using the Visual C ++ compiler. Now I want to port it to linux, but there is something strange that happens after compilation on Linux.

So, I'm trying to iterate over a list using an iterator. Here is the code:

for (list<IntermediateRepresentation>::iterator irIt = funcIt->second.prologue.begin(); irIt != funcIt->second.prologue.end(); ++irIt) {
    irIt->address = address;
    address += getOpcodeSize(irIt->opcode);
}

Now the problem is that the code above causes an infinite loop. I tried to understand why this happens in the debugger, and I found out that the last element of the list (the one before the "end ()") pointed to the begin () iterator instead of the "end" () ', so when I called "+ + irIt ", he returned to" begin () ". Is this expected behavior? And one more thing I discovered is that when I do this:

size_t irSize = funcIt->second.prologue.size();

which causes an infinite loop, as it calculates the size using a loop like mine. So you can't expect the behavior to be right?

Can someone tell me where there might be a problem?

Oh, and I'm using Ubuntu 12.10, g ++ version 4.7.2 and the eclipse IDE with Linux GCC as a toolchain.

Thank!

+5
source share
1 answer

You probably created an invalid std :: list by splicing in yourself.

For example, using the third splice option :

void splice(const_iterator pos, list& other, 
            const_iterator first, const_iterator last);

3) Moves items in the range [first, last)from otherto *this. Elements are inserted before the element that they point to pos. The behavior is undefined if it posis an iterator in a range [first,last).

+5

All Articles