Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ list iterator never reaches end() when iterating through

Ok, I wrote a program which runs perfectly fine when compiled with Visual C++ compiler. Now I want to port it to linux but there is a wierd stuff happening after I compile it in linux.

So, I am trying to loop through a list using an iterator. Here 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 above code causes infinite loop. I tried to see why it was doing so in the debugger and I found out that the last element of the list (one that is just before 'end()') was pointing to the 'begin()' iterator instead of 'end()' iterator so when I called '++irIt', it went back to 'begin()'. Is that an expected behaviour? And another thing I found is that when I do this:

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

that causes infinite loop too since it calculates the size using a loop similar to mine. So, it can't be expected behaviour right?

Can anyone give me some hint as where the problem might be?

Oh, and I am using Ubuntu 12.10, g++ version 4.7.2, and eclipse IDE with Linux GCC as toolchain.

Thanks!

like image 228
Pradipna Nepal Avatar asked Feb 22 '13 08:02

Pradipna Nepal


1 Answers

You have likely created an invalid std::list by splicing in into itself.

For example, usage of the third variation of splice:

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

3) Moves the elements in the range [first, last) from other into *this. The elements are inserted before the element pointed to by pos. The behavior is undefined if pos is an iterator in the range [first,last).

like image 102
Peter Wood Avatar answered Sep 25 '22 13:09

Peter Wood