0

I'm having an inconsistent behavior for a piece of code. If processorNodes.size() is 0, then this loop should never start:

ALOGV(TAG, "updateGraph, processorNodes.size()-1: %d", processorNodes.size()-1);
for (int i = 0; i < processorNodes.size() - 1; ++i)
{
    ALOGV(TAG, "acessing node at %d", i);
    for (int channel = 0; channel < 2; ++channel)
        mainProcessor->addConnection ({ { processorNodes.at(i)->nodeID,      channel },
                                        { processorNodes.at(i+1)->nodeID,  channel } });
}

But here's the output:

V/ProcessorGraph.cpp: updateGraph, processorNodes.size()-1: -1
    acessing node at 0
E/libc++abi: terminating with uncaught exception of type std::out_of_range: map::at:  key not found

As you see, it throws an exception because it tries to access something that does not exist at i=0.

What is wrong?

I simulated

int main()
{
    for (int i=0; i<-1; i++) {
        std::cout << "hello" << std::endl;
    }
}

and it simply does not run. Why my loop runs?

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • 6
    `processorNodes.size()` is unsigned, so the integer overflows and wraps around. – iz_ May 19 '21 at 22:47
  • 6
    With warning enabled, your compiler would probably notice you about that fishy comparison. – YSC May 19 '21 at 22:49
  • `for (int i=0; i<-1; i++)` definitely doesn't run. But that's not the code in your question – phuclv May 20 '21 at 00:19

0 Answers0