V1044. Loop break conditions do not depend on the number of iterations.


The analyzer has detected a loop whose termination conditions do not depend on the number of iterations. Such a loop may execute 0 or 1 times or become an infinite loop.

Example of incorrect loop:

void sq_settop(HSQUIRRELVM v, SQInteger newtop)
{
  SQInteger top = sq_gettop(v);
  if(top > newtop)
    sq_pop(v, top - newtop);
  else
    while(top < newtop) sq_pushnull(v); // <=
}

The error is found in the while loop: the values of the variables participating in the conditional expression do not change, so the loop will never terminate or start at all (if the variables are equal).

The loop can always execute only once if its condition is changed during the first iteration:

while (buf != nullptr && buf != ntObj)
{
  ntObj = buf;
}

If this behavior is deliberate, it is better to rewrite the loop as an if-statement:

if (buf != nullptr && buf != ntObj)
{
  ntObj = buf;
}

Another example:

#define PEEK_WORD(ptr)      *((uint16*)(ptr))
....
for(;;)
{
  // Verify the packet size
  if (dwPacketSize >= 2)
  {
    dwMsgLen = PEEK_WORD(pbytePacket);
    if ((dwMsgLen + 2) == dwPacketSize)
      break;
  }
  throw CString(_T("invalid message packet"));
}

Executing any branch of this loop causes it to terminate, and the variables handled inside it will never change. This loop must be incorrect or is simply unnecessary and should be removed.


Bugs Found

Checked Projects
364
Collected Errors
13 504