metrica
Мы используем куки, чтобы пользоваться сайтом было удобно.
Хорошо
to the top
close form

Заполните форму в два простых шага ниже:

Ваши контактные данные:

Шаг 1
Поздравляем! У вас есть промокод!

Тип желаемой лицензии:

Шаг 2
Team license
Enterprise license
** Нажимая на кнопку, вы даете согласие на обработку
своих персональных данных. См. Политику конфиденциальности
close form
Запросите информацию о ценах
Новая лицензия
Продление лицензии
--Выберите валюту--
USD
EUR
RUB
* Нажимая на кнопку, вы даете согласие на обработку
своих персональных данных. См. Политику конфиденциальности

close form
Бесплатная лицензия PVS‑Studio для специалистов Microsoft MVP
* Нажимая на кнопку, вы даете согласие на обработку
своих персональных данных. См. Политику конфиденциальности

close form
Для получения лицензии для вашего открытого
проекта заполните, пожалуйста, эту форму
* Нажимая на кнопку, вы даете согласие на обработку
своих персональных данных. См. Политику конфиденциальности

close form
Мне интересно попробовать плагин на:
* Нажимая на кнопку, вы даете согласие на обработку
своих персональных данных. См. Политику конфиденциальности

close form
check circle
Ваше сообщение отправлено.

Мы ответим вам на


Если вы так и не получили ответ, пожалуйста, проверьте папку
Spam/Junk и нажмите на письме кнопку "Не спам".
Так Вы не пропустите ответы от нашей команды.

Вебинар: Трудности при интеграции SAST, как с ними справляться - 04.04

>
>
>
Примеры ошибок, обнаруженных с помощью …

Примеры ошибок, обнаруженных с помощью диагностики V547

V547. Expression is always true/false.


Shareaza

V547 Expression 'pBytes [ 0 ] == 0xEF' is always false. The value range of signed char type: [-128, 127]. Shareaza remote.cpp 350


void CRemote::Output(LPCTSTR pszName)
{

  ....
  CHAR* pBytes = new CHAR[ nBytes ];
  hFile.Read( pBytes, nBytes );
  ....
  if ( nBytes > 3 &&
       pBytes[0] == 0xEF &&
       pBytes[1] == 0xBB &&
       pBytes[2] == 0xBF )
  {
    pBytes += 3;
    nBytes -= 3;
    bBOM = true;
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'pBytes [ 1 ] == 0xBB' is always false. The value range of signed char type: [-128, 127]. Shareaza remote.cpp 350
  • V547 Expression 'pBytes [ 2 ] == 0xBF' is always false. The value range of signed char type: [-128, 127]. Shareaza remote.cpp 350

Shareaza

V547 Expression is always false. Unsigned type value is never < 0. BugTrap encoding.cpp 425


size_t UTF16BeDecodeChar(BYTE* pBytes, size_t nNumBytes,
                         TCHAR arrChar[2], size_t& nCharSize)
{
  if (UTF16BeToLeChar(pBytes, nNumBytes) < 0)
  {
    nCharSize = MAXSIZE_T;
    return 0;
  }
  return UTF16LeDecodeChar(pBytes, nNumBytes,
                           arrChar, nCharSize);
}

In case of an error, the UTF16BeToLeChar() function returns MAXSIZE_T. This case will be handled incorrectly.


Shareaza

V547 Expression 'nCharPos >= 0' is always true. Unsigned type value is always >= 0. BugTrap xmlreader.h 946


inline void CXmlReader::CXmlInputStream::UnsafePutCharsBack(
  const TCHAR* pChars, size_t nNumChars)
{
  if (nNumChars > 0)
  {
    for (size_t nCharPos = nNumChars - 1;
         nCharPos >= 0;
         --nCharPos)
      UnsafePutCharBack(pChars[nCharPos]);
  }
}

Infinite loop.


VirtualDub

V547 Expression 'c < 0' is always false. Unsigned type value is never < 0. Ami lexer.cpp 225


typedef unsigned short wint_t;

void lexungetc(wint_t c) {
  if (c < 0)
    return;

  g_backstack.push_back(c);
}

VirtualDub

V547 Expression 'c < 0' is always false. Unsigned type value is never < 0. Ami lexer.cpp 279


typedef unsigned short wint_t;

wint_t lexgetescape() {
  wint_t c = lexgetc();
  if (c < 0)
    fatal("Newline found in escape sequence");
  ....
}

Geocoding with SQL-Server

V547 Expression '* s > 127' is always false. The value range of signed char type: [-128, 127]. Shp2Xml shp2xml.cpp 18


char *chkXml(char *buf) {
 for (char *s = buf; *s; s++)
   if (*s == '&') *s = '/';
   ....
   else if (*s > 127) *s = '~';
 return buf;
}

Ultimate TCP/IP

V547 Expression '( len - indx ) >= 0' is always true. Unsigned type value is always >= 0. UTDns utstrlst.cpp 58


void CUT_StrMethods::RemoveCRLF(LPSTR buf)
{
  // v4.2 changed to size_t
  size_t  len, indx = 1;
  if(buf != NULL){
    len = strlen(buf);
    while((len - indx) >= 0 && indx <= 2) {
      if(buf[len - indx] == '\r' ||
         buf[len - indx] == '\n')
         buf[len - indx] = 0;
      ++indx;
    }
  }
}

This is an example of potential vulnerability. When processing an empty string, the (len - indx) expression will equal 0xFFFFFFFFu. The value 0xFFFFFFFFu is above 0. An array overrun will occur.

Similar errors can be found in some other places:

  • V547 Expression '( len - indx ) >= 0' is always true. Unsigned type value is always >= 0. UTDns utstrlst.cpp 75

Ultimate TCP/IP

V547 Expression 'loop >= 0' is always true. Unsigned type value is always >= 0. UTDns utstrlst.cpp 430


void CUT_StrMethods::RemoveSpaces(LPSTR szString) {
  ....
  size_t loop, len = strlen(szString);
  // Remove the trailing spaces
  for(loop = (len-1); loop >= 0; loop--) {
    if(szString[loop] != ' ')
      break;
  }
  ....
}

An example of potential vulnerability. If a string contains only blanks, an array overrun will occur.

Similar errors can be found in some other places:

  • V547 Expression 'loop >= 0' is always true. Unsigned type value is always >= 0. UTDns utstrlst.cpp 458

Ultimate TCP/IP

V547 Expression 'buf[t] > 127' is always false. The value range of signed char type: [-128, 127]. UTImap4 utmime.cpp 320


int CUT_MimeEncode::Encode7bit(....)
{
  ....
  char buf[1000];
  ....
  for ( t=0; t<bytesRead; t++ ) {
    if (buf[t]==0 || buf[t]>127) {
      retval = UTE_ENCODING_INVALID_CHAR;
      break;
    }
  ....
}

Ultimate Toolbox

V547 Expression 'lpDrawItemStruct -> itemID >= 0' is always true. Unsigned type value is always >= 0. UT oxautolistbox.cpp 56


void COXAutoListBox::DrawItem(....)
{
  ....
  if (lpDrawItemStruct->itemID>=0)
  {
    ....
  }
  ....
}

Most likely this is what should be written here: (lpDrawItemStruct->itemID != (UINT)(-1))


Ultimate Toolbox

V547 Expression 'lpms -> itemID < 0' is always false. Unsigned type value is never < 0. UT oxcoolcombobox.cpp 476


void COXCoolComboBox::MeasureItem(....)
{
  if(lpms->itemID<0)
    lpms->itemHeight=m_nDefaultFontHeight+1;
  else
    lpms->itemHeight=
      m_nDefaultFontHeightSansLeading+1;
}

Ultimate Toolbox

V547 Expression 'chNewChar >= 128' is always false. The value range of signed char type: [-128, 127]. UT oxmaskededit.cpp 81


BOOL CMaskData::IsValidInput(TCHAR chNewChar)
{
   ....
  if((chNewChar >= 128) && (chNewChar <= 255))
    bIsValidInput=TRUE ;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'chNewChar <= 255' is always true. The value range of signed char type: [-128, 127]. UT oxmaskededit.cpp 81

Ultimate Toolbox

V547 Expression 'm_nCurrentIndex - nOffset < 0' is always false. Unsigned type value is never < 0. UT oxprocess.cpp 594


int m_nCurrentIndex;
....
BOOL COXProcessIterator::Prev(UINT nOffset)
{
  ....
  if(m_nCurrentIndex-nOffset<0)
    return FALSE;
  ....
}

Since the "m_nCurrentIndex-nOffset" expression has the unsigned type, it can never be below 0.


TortoiseSVN

V547 Expression 'c >= 0x80' is always false. The value range of signed char type: [-128, 127]. pathutils.cpp 559


CString CPathUtils::PathUnescape (const char* path)
{
  // try quick path
  size_t i = 0;
  for (; char c = path[i]; ++i)
    if ((c >= 0x80) || (c == '%'))
    {
      // quick path does not work for
      // non-latin or escaped chars
      std::string utf8Path (path);
      CPathUtils::Unescape (&utf8Path[0]);
      return CUnicodeUtils::UTF8ToUTF16 (utf8Path);
    }
  ....
}

TortoiseSVN

V547 Expression '* utf8CheckBuf == 0xC0' is always false. The value range of signed char type: [-128, 127]. tortoiseblame.cpp 310


BOOL TortoiseBlame::OpenFile(const TCHAR *fileName)
{
  ....
  // check each line for illegal utf8 sequences.
  // If one is found, we treat
  // the file as ASCII, otherwise we assume
  // an UTF8 file.
  char * utf8CheckBuf = lineptr;
  while ((bUTF8)&&(*utf8CheckBuf))
  {
    if ((*utf8CheckBuf == 0xC0)||
        (*utf8CheckBuf == 0xC1)||
        (*utf8CheckBuf >= 0xF5))
    {
      bUTF8 = false;
      break;
    }

   ....
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression '* utf8CheckBuf == 0xC1' is always false. The value range of signed char type: [-128, 127]. tortoiseblame.cpp 311
  • V547 Expression '* utf8CheckBuf >= 0xF5' is always false. The value range of signed char type: [-128, 127]. tortoiseblame.cpp 312

TortoiseSVN

V547 Expression 'endRevision < 0' is always false. Unsigned type value is never < 0. cachelogquery.cpp 999


typedef index_t revision_t;
....
void CCacheLogQuery::InternalLog (
   revision_t startRevision
 , revision_t endRevision
 , const CDictionaryBasedTempPath& startPath
 , int limit
 , const CLogOptions& options)
{
  ....
  // we cannot receive logs for rev < 0
  if (endRevision < 0)
    endRevision = 0;

  ....
}

Negative values simply cannot appear here. The endRevision variable has the unsigned type and, therefore, endRevision is always >=0. The potential danger is this: if a negative value was cast to the unsigned type somewhere before, we will be handling a very big number. And there's no check for that.


TraceTool

V547 Expression '(m_socketHandle = socket (2, 1, 0)) < 0' is always false. Unsigned type value is never < 0. Vs8_Win_Lib tracetool.cpp 871


static UINT_PTR m_socketHandle ;

void TTrace::LoopMessages(void)
{
  ....
  // Socket creation
  if ( (m_socketHandle = socket(AF_INET,SOCK_STREAM,0)) < 0)
  {
    continue;
  }
  ....
}

FCEUX

V547 Expression 'x < 0' is always false. Unsigned type value is never < 0. fceux gui.cpp 32


void CenterWindow(HWND hwndDlg)
{
  ....
  unsigned x = ((rectP.right-rectP.left) - width) / 2 +
               rectP.left;
  unsigned y = ((rectP.bottom-rectP.top) - height) / 2 +
               rectP.top;
  ....
  // make sure that the dialog box never moves outside
  // of the screen
  if(x < 0) x = 0;
  if(y < 0) y = 0;
  if(x + width  > screenwidth)  x = screenwidth  - width;
  if(y + height > screenheight) y = screenheight - height;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'y < 0' is always false. Unsigned type value is never < 0. fceux gui.cpp 33

IPP Samples

V547 Expression '* pTrack >= 0' is always true. Unsigned type value is always >= 0. demuxer umc_stream_parser.cpp 179


typedef signed int     Ipp32s;
typedef unsigned int   Ipp32u;

Ipp32s StreamParser::GetTrackByPidOrCreateNew(Ipp32s iPid,
                                              bool *pIsNew)
{
  ....
  else if (!pIsNew || m_uiTracks >= MAX_TRACK)
    return -1;
  ....
}

Status StreamParser::GetNextData(MediaData *pData,
                                 Ipp32u *pTrack)
{
  ....
  *pTrack = GetTrackByPidOrCreateNew(m_pPacket->iPid, NULL);

  if (*pTrack >= 0 && TRACK_LPCM == m_pInfo[*pTrack]->m_Type)
    ippsSwapBytes_16u_I((Ipp16u *)pData->GetDataPointer(),
                        m_pPacket->uiSize / 2);
  ....
}

IPP Samples

V547 Expression 'memSize < 0' is always false. Unsigned type value is never < 0. vc1_enc umc_vc1_enc_planes.h 200


typedef unsigned int    Ipp32u;

UMC::Status Init(..., Ipp32u memSize, ...)
{
  ....
  memSize -= UMC::align_value<Ipp32u>(m_nFrames*sizeof(Frame));
  if(memSize < 0)
      return UMC::UMC_ERR_NOT_ENOUGH_BUFFER;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'memSize < 0' is always false. Unsigned type value is never < 0. vc1_enc umc_vc1_enc_planes.h 211
  • V547 Expression 'memSize < 0' is always false. Unsigned type value is never < 0. vc1_enc umc_vc1_enc_mb.cpp 64
  • V547 Expression 'memSize < 0' is always false. Unsigned type value is never < 0. vc1_enc umc_vc1_enc_mb.cpp 73
  • And 5 additional diagnostic messages.

IPP Samples

V547 Expression 'm_iCurrMBIndex - x < 0' is always false. Unsigned type value is never < 0. vc1_enc umc_vc1_enc_mb.cpp 188


Ipp32u m_iCurrMBIndex;

VC1EncoderMBInfo *
VC1EncoderMBs::GetPevMBInfo(Ipp32s x, Ipp32s y)
{
   Ipp32s row = (y>0)? m_iPrevRowIndex:m_iCurrRowIndex;
   return ((m_iCurrMBIndex - x <0 || row <0) ?
          0 :
          &m_MBInfo[row][m_iCurrMBIndex - x]);
}

Since the check doesn't work, we may easily get an array overrun.


DOSBox

V547 Expression is always true. Unsigned type value is always >= 0. dosbox libserial.cpp 155


void SERIAL_getErrorString(char* buffer, int length) {
  ....
  if((length - sysmsg_offset -
      strlen((const char*)sysmessagebuffer)) >= 0)
     memcpy(buffer + sysmsg_offset, sysmessagebuffer,
            strlen((const char*)sysmessagebuffer));
  ....
}

This is an example of unsafe code from the viewpoint of buffer overflows. The strlen() function returns size_t. It means that the check for buffer overflow doesn't work.


Miranda IM

V547 Expression 'newItem >= 0' is always true. Unsigned type value is always >= 0. avs options.cpp 265


INT_PTR CALLBACK DlgProcOptionsProtos(....)
{
  ....
  UINT64 newItem = 0;
  ....
  newItem = ListView_InsertItem(hwndList, &item);
  if(newItem >= 0)
    ListView_SetCheckState(....);
  ....
}

Miranda IM

V547 Expression 'nGroupsCount < 0' is always false. Unsigned type value is never < 0. import mirabilis.c 1416


extern DWORD nMessagesCount;

static void MirabilisImport(HWND hdlgProgressWnd)
{
  ....
  nGroupsCount = ImportGroups();
  if (nGroupsCount < 0) {
    AddMessage( LPGEN("Group import was not completed."));
    nGroupsCount = 0;
  }
  ....
}

Miranda IM

V547 Expression 'wParam >= 0' is always true. Unsigned type value is always >= 0. clist_mw cluiframes.c 3140


typedef UINT_PTR WPARAM;

static int id2pos(int id)
{
  int i;
  if (FramesSysNotStarted) return -1;
  for (i=0;i<nFramescount;i++)
  {
    if (Frames[i].id==id) return(i);
  }
  return(-1);
}

INT_PTR CLUIFrameSetFloat(WPARAM wParam,LPARAM lParam)
{
  ....
  wParam=id2pos(wParam);
  if(wParam>=0&&(int)wParam<nFramescount)
    if (Frames[wParam].floating)
  ....
}

Miranda IM

V547 Expression is always true. Unsigned type value is always >= 0. scriver msgoptions.c 458


WINUSERAPI
UINT
WINAPI
GetDlgItemInt(
    __in HWND hDlg,
    __in int nIDDlgItem,
    __out_opt BOOL *lpTranslated,
    __in BOOL bSigned);

#define SRMSGSET_LIMITNAMESLEN_MIN 0

static INT_PTR CALLBACK DlgProcTabsOptions(....)
{
  ....
  limitLength =
    GetDlgItemInt(hwndDlg, IDC_LIMITNAMESLEN, NULL, TRUE) >=
    SRMSGSET_LIMITNAMESLEN_MIN ?
    GetDlgItemInt(hwndDlg, IDC_LIMITNAMESLEN, NULL, TRUE) :
    SRMSGSET_LIMITNAMESLEN_MIN;
  ....
}

Miranda IM

V547 Expression 'nOldLength < 0' is always false. Unsigned type value is never < 0. IRC mstring.h 229


void Append( PCXSTR pszSrc, int nLength )
{
  ....
  UINT nOldLength = GetLength();
  if (nOldLength < 0)
  {
    // protects from underflow
    nOldLength = 0;
  }
  ....
}

Miranda IM

V547 Expression 'ft->std.currentFileSize < 0' is always false. Unsigned type value is never < 0. jabber jabber_file.cpp 92


typedef struct tagPROTOFILETRANSFERSTATUS
{
  ....
  unsigned __int64 currentFileSize;
  ....
} PROTOFILETRANSFERSTATUS;

//There is this place in the program code:
ft->std.currentFileSize = -1;


void __cdecl CJabberProto::FileReceiveThread(filetransfer* ft)
{
  ....
  if (ft->state==FT_DONE ||
      ( ft->state==FT_RECEIVING && ft->std.currentFileSize < 0 ))
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'ft->std.currentFileSize < 0' is always false. Unsigned type value is never < 0. jabber jabber_file.cpp 168

StrongDC++

V547 Expression 'totalsize < 0' is always false. Unsigned type value is never < 0. client queuemanager.cpp 2230


uint64_t QueueManager::FileQueue::getTotalQueueSize(){
  uint64_t totalsize = 0;
  ....
  if(totalsize < 0)
    totalsize = 0;
  ....
}

Chromium

V547 Expression 'current_idle_time < 0' is always false. Unsigned type value is never < 0. browser idle_win.cc 23


IdleState CalculateIdleState(unsigned int idle_threshold) {
  ....
  DWORD current_idle_time = 0;
  ....
  // Will go -ve if we have been idle for
  // a long time (2gb seconds).
  if (current_idle_time < 0)
    current_idle_time = INT_MAX;
  ....
}

Chromium

V547 Expression 'count < 0' is always false. Unsigned type value is never < 0. ncdecode_tablegen ncdecode_tablegen.c 197


static void CharAdvance(char** buffer,
                        size_t* buffer_size,
                        size_t count) {
  if (count < 0) {
    NaClFatal("Unable to advance buffer by count!");
  } else {
  ....
}

ICU

V547 Expression '* string != 0 || * string != '_'' is always true. Probably the '&&' operator should be used here. icui18n ucol_sit.cpp 242


U_CDECL_BEGIN static const char* U_CALLCONV
_processVariableTop(....)
{
  ....
  if(i == locElementCapacity &&
     (*string != 0 || *string != '_')) {
    *status = U_BUFFER_OVERFLOW_ERROR;
  }
  ....
}

Network Security Services (NSS)

V547 Expression 'input.len < 0' is always false. Unsigned type value is never < 0. nss pk11merge.c 491


struct SECItemStr {
  ....
  unsigned int len;
};

static SECStatus
pk11_mergeSecretKey(....)
{
  ....
  if (input.len < 0) {
    rv = SECFailure;
    goto done;
  }
  ....
}

Qt

V547 Expression '-- size >= 0' is always true. Unsigned type value is always >= 0. QtCLucene arrays.h 154


bool equals( class1* val1, class2* val2 ) const{
{
  ....
  size_t size = val1->size();
  ....
  while ( --size >= 0 ){
    if ( !comp(*itr1,*itr2) )
      return false;
    itr1++;
    itr2++;
  }
  ....
}

An array overrun may surely occur.


Qt

V547 Expression 'q->getQueryName () != L"BooleanQuery"' is always true. To compare strings you should use wcscmp() function. QtCLucene multifieldqueryparser.cpp 44


const TCHAR* getQueryName() const;

Query* MultiFieldQueryParser::parse(....)
{
  ....
  if (q && (q->getQueryName() != _T("BooleanQuery")
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'q->getQueryName () != L"BooleanQuery"' is always true. To compare strings you should use wcscmp() function. QtCLucene multifieldqueryparser.cpp 63

MySQL

V547 Expression 'str [0] != 'a' || str [0] != 'A'' is always true. Probably the '&&' operator should be used here. clientlib my_time.c 340


enum enum_mysql_timestamp_type
str_to_datetime(....)
{
  ....
  else if (str[0] != 'a' || str[0] != 'A')
    continue; /* Not AM/PM */
  ....
}

Apache HTTP Server

V547 Expression 'len < 0' is always false. Unsigned type value is never < 0. aprutil apr_memcache.c 814


typedef  size_t      apr_size_t;

APU_DECLARE(apr_status_t) apr_memcache_getp(....)
{
  ....
  apr_size_t len = 0;
  ....
  len = atoi(length);
  ....
  if (len < 0) {
    *new_length = 0;
    *baton = NULL;
  }
  else {
    ....
  }
}

Apache HTTP Server

V547 Expression 'csd < 0' is always false. Unsigned type value is never < 0. libhttpd child.c 404


typedef UINT_PTR SOCKET;

static unsigned int __stdcall win9x_accept(void * dummy)
{
  SOCKET csd;
  ....
  do {
      clen = sizeof(sa_client);
      csd = accept(nsd, (struct sockaddr *) &sa_client, &clen);
  } while (csd < 0 &&
           APR_STATUS_IS_EINTR(apr_get_netos_error()));
  ....
}

Intel AMT SDK

V547 Expression '_username == ""' is always false. To compare strings you should use strcmp() function. Discovery discoverysample.cpp 184


static char* _username = "";
static char* _password = "";
static char* _host = "";
static char* _hostMask = "";

if (((_username == "") && (_password != "")) ||
    ((_username != "") && (_password == "")))

This code is dangerous and incorrect. But sometimes it will work - when the whole code is in one module (one *.obj). The compiler will create only one empty string in memory.


Intel AMT SDK

V547 Expression 'bytesRead < 0' is always false. Unsigned type value is never < 0. RemoteConsole remote.c 173


int ReadFileData(char* fileName, UINT8 data[], size_t size)
{
  size_t fileSize , bytesRead;
  ....
  bytesRead = read(fileno(fileHandle), data, (int) size);

  if (bytesRead < 0)
  {
    printf("Error while Reading file %s : %s",
           fileName, strerror(errno));
    bytesRead = 0;
  }
  ....
}

Intel AMT SDK

V547 Expression 'bytesRead < 0' is always false. Unsigned type value is never < 0. ZTCLocalAgent heciwin.cpp 357


int HECIWin::_doIoctl(....)
{
  DWORD bytesRead = 0;
  ....
  if (bytesRead < 0) {
    Deinit();
  }
  ....
}

TrueCrypt

V547 Expression 'fileDataEndPos < 0' is always false. Unsigned type value is never < 0. Setup selfextract.c 551


BOOL SelfExtractInMemory (char *path)
{
  unsigned int fileDataEndPos = 0;
  ....
  if (fileDataEndPos < 0)
  {
    Error ("CANNOT_READ_FROM_PACKAGE");
    return FALSE;
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'fileDataStartPos < 0' is always false. Unsigned type value is never < 0. Setup selfextract.c 560

ReactOS

V547 Expression is always false. Probably the '||' operator should be used here. ws2_32_new sockctrl.c 55


INT
WSAAPI
connect(IN SOCKET s,
        IN CONST struct sockaddr *name,
        IN INT namelen)
{
  ....
  /* Check if error code was due to the host not being found */
  if ((Status == SOCKET_ERROR) &&
      (ErrorCode == WSAEHOSTUNREACH) &&
      (ErrorCode == WSAENETUNREACH))
  {
  ....
}

ReactOS

V547 Expression is always true. Probably the '&&' operator should be used here. win32k arc.c 67


typedef enum _ARCTYPE
{
    GdiTypeArc,
    GdiTypeArcTo,
    GdiTypeChord,
    GdiTypePie,
} ARCTYPE, *PARCTYPE;

BOOL IntArc(....)
{
  ....
  if ((Left == Right) ||
      (Top == Bottom) ||
      (((arctype != GdiTypeArc) ||
        (arctype != GdiTypeArcTo)) &&
       ((Right - Left == 1) ||
       (Bottom - Top == 1))
      )
     )
      return TRUE;
  ....
}

Most likely this is what should be written here: (arctype != GdiTypeArc) && (arctype != GdiTypeArcTo)


ReactOS

V547 Expression 'LeftOfBuffer < 0' is always false. Unsigned type value is never < 0. svchost svchost.c 56


BOOL PrepareService(LPCTSTR ServiceName)
{
  DWORD LeftOfBuffer = sizeof(ServiceKeyBuffer) /
                       sizeof(ServiceKeyBuffer[0]);
  ....
  LeftOfBuffer -= _tcslen(SERVICE_KEY);
  ....
  LeftOfBuffer -= _tcslen(ServiceName);
  ....
  LeftOfBuffer -= _tcslen(PARAMETERS_KEY);
  ....
  if (LeftOfBuffer < 0)
  {
    DPRINT1("Buffer overflow for service name: '%s'\n",
            ServiceName);
    return FALSE;
  }
  ....
}

There are a lot of such fragments in ReactOS, but I cannot say for sure how critical they are.


ReactOS

V547 Expression '(Minor != 0x02) || (Minor != 0x13)' is always true. Probably the '&&' operator should be used here. ramdisk ramdisk.c 1955


#define IRP_MN_REMOVE_DEVICE      0x02
#define IRP_MN_QUERY_ID           0x13

NTSTATUS
RamdiskPnp(IN PDEVICE_OBJECT DeviceObject,
           IN PIRP Irp)
{
  ....
  // Only remove-device and query-id are allowed
  if ((Minor != IRP_MN_REMOVE_DEVICE) ||
      (Minor != IRP_MN_QUERY_ID))
  ....
}

This is what should have been written here: ((Minor == IRP_MN_REMOVE_DEVICE) || (Minor == IRP_MN_QUERY_ID))

Similar errors can be found in some other places:

  • V547 Expression is always true. Probably the '&&' operator should be used here. ntoskrnl section.c 1685
  • V547 Expression is always true. Probably the '&&' operator should be used here. fastfat create.c 456

ReactOS

V547 Expression is always false. Unsigned type value is never < 0. opengl32 font.c 1099


BOOL APIENTRY IntUseFontOutlinesW(....)
{
  ....
  if (GetGlyphOutline(hDC, glyphIndex, GGO_NATIVE,
       &glyphMetrics, glyphBufSize, glyphBuf, &matrix) < 0)
  {
    HeapFree(GetProcessHeap(), 0, glyphBuf);
    return FALSE; /*WGL_STATUS_FAILURE*/
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'glyphSize < 0' is always false. Unsigned type value is never < 0. opengl32 font.c 1084

ReactOS

V547 Expression 'IntEaLength >= 0' is always true. Unsigned type value is always >= 0. ntoskrnl util.c 220


NTSTATUS
IoCheckEaBufferValidity(....)
{
  ULONG NextEaBufferOffset, IntEaLength;
  ....
  if (IntEaLength >= 0)
  {
    EaBufferEnd = (PFILE_FULL_EA_INFORMATION)
      ((ULONG_PTR)EaBufferEnd +
      EaBufferEnd->NextEntryOffset);
    continue;
  }
}

Similar errors can be found in some other places:

  • V547 Expression 'IntEaLength >= 0' is always true. Unsigned type value is always >= 0. ntoskrnl util.c 198

ReactOS

V547 Expression 'i < 512' is always true. The value range of unsigned char type: [0, 255]. freeldr_common xboxhw.c 344


static VOID
DetectBiosDisks(....)
{
  UCHAR DiskCount, i;
  ....
  for (i = 0; ! Changed && i < 512; i++)
  {
    Changed = ((PUCHAR)DISKREADBUFFER)[i] != 0xcd;
  }
  ....
}

An infinite loop will occur here if the first 255 bytes contain value 0xcd.

Similar errors can be found in some other places:

  • V547 Expression 'i < 512' is always true. The value range of unsigned char type: [0, 255]. freeldr_common hardware.c 826

ReactOS

V547 Expression 'ads->tcpsocket >= 0' is always true. Unsigned type value is always >= 0. adns setup.c 683


typedef UINT_PTR SOCKET;

#define ADNS_SOCKET SOCKET

struct adns__state {
  ....
  ADNS_SOCKET udpsocket, tcpsocket;
  ....
};

void adns_finish(adns_state ads) {
  ....
  if (ads->tcpsocket >= 0) adns_socket_close(ads->tcpsocket);
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'ads->udpsocket < 0' is always false. Unsigned type value is never < 0. adns setup.c 539
  • V547 Expression 'fd < 0' is always false. Unsigned type value is never < 0. adns event.c 117

Chromium

V547 Expression is always true. Probably the '&&' operator should be used here. webrtc_vplib interpolator.cc 119


WebRtc_Word32
interpolator::SupportedVideoType(VideoType srcVideoType,
                                 VideoType dstVideoType)
{
  ....
  if ((srcVideoType != kI420) ||
      (srcVideoType != kIYUV) ||
      (srcVideoType != kYV12))
  {
      return -1;
  }
  ....
}

Mozilla Firefox

V547 Expression 'c < 0' is always false. Unsigned type value is never < 0. updater.cpp 1179


int
PatchFile::LoadSourceFile(FILE* ofile)
{
  ....
  size_t c = fread(rb, 1, r, ofile);
  if (c < 0) {
    LOG(("LoadSourceFile: error reading destination file: "
         LOG_S "\n", mFile));
    return READ_ERROR;
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'c < 0' is always false. Unsigned type value is never < 0. updater.cpp 2373
  • V547 Expression 'c < 0' is always false. Unsigned type value is never < 0. bspatch.cpp 107

Mozilla Firefox

V547 Expression is always true. Unsigned type value is always >= 0. exception_handler.cc 846


bool ExceptionHandler::WriteMinidumpForChild(....)
{
  ....
  DWORD last_suspend_cnt = -1;
  ....
  // this thread may have died already, so not opening
  // the handle is a non-fatal error
  if (NULL != child_thread_handle) {
    if (0 <=
        (last_suspend_cnt = SuspendThread(child_thread_handle)))
    {
  ....
}

Most likely this is what should be written here: (((DWORD) -1) != (last_suspend_cnt = SuspendThread(child_thread_handle))).

Similar errors can be found in some other places:

  • V547 Expression '0 <= last_suspend_cnt' is always true. Unsigned type value is always >= 0. exception_handler.cc 869

Mozilla Firefox

V547 Expression 'index < 0' is always false. Unsigned type value is never < 0. nsieprofilemigrator.cpp 622


PRBool
nsIEProfileMigrator::TestForIE7()
{
  ....
  PRUint32 index = ieVersion.FindChar('.', 0);
  if (index < 0)
    return PR_FALSE;
  ....
}

Notepad++

V547 Expression is always false. Probably the '||' operator should be used here. Notepad++ notepad_plus.cpp 4967


DWORD WINAPI Notepad_plus::threadTextPlayer(void *params)
{
  ....
  const char *text2display = ...;
  ....
  if (text2display[i] == ' ' && text2display[i] == '.')
  ....
}

Similar errors can be found in some other places:

  • V547 Expression is always false. Probably the '||' operator should be used here. Notepad++ notepad_plus.cpp 5032

ADAPTIVE Communication Environment (ACE)

V547 Expression 'ch != '_' || ch != ':'' is always true. Probably the '&&' operator should be used here. ACEXML_Parser parser.cpp 1905


ACEXML_Char*
ACEXML_Parser::parse_reference_name (void)
{
  ACEXML_Char ch = this->get ();
  if (!this->isLetter (ch) && (ch != '_' || ch != ':'))
    return 0;
  ....
}

WinMerge

V547 Expression 'cchText < 0' is always false. Unsigned type value is never < 0. Merge ccrystaleditview.cpp 1135


BOOL CCrystalEditView::
DoDropText (COleDataObject * pDataObject,
            const CPoint & ptClient)
{
  ....
  UINT cbData = (UINT) ::GlobalSize (hData);
  UINT cchText = cbData / sizeof(TCHAR) - 1;
  if (cchText < 0)
    return FALSE;
  ....
}

BCmenu

V547 Expression 'nLoc >= 0' is always true. Unsigned type value is always >= 0. Merge bcmenu.cpp 1232


BCMenu *BCMenu::FindMenuOption(int nId,UINT& nLoc)
{
  ....
  nLoc = -1;
  ....
}

BOOL BCMenu::ModifyODMenuW(wchar_t *lpstrText,
                           UINT nID, int nIconNormal)
{
  UINT nLoc;
  ....
  BCMenu *psubmenu = FindMenuOption(nID,nLoc);
  ....
  if(psubmenu && nLoc>=0) mdata = psubmenu->m_MenuList[nLoc];
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'nLoc >= 0' is always true. Unsigned type value is always >= 0. Merge bcmenu.cpp 1263
  • V547 Expression 'nLoc >= 0' is always true. Unsigned type value is always >= 0. Merge bcmenu.cpp 1285
  • V547 Expression 'nLoc >= 0' is always true. Unsigned type value is always >= 0. Merge bcmenu.cpp 1309
  • And 2 additional diagnostic messages.

WinMerge

V547 Expression 'text.length() >= 0' is always true. Unsigned type value is always >= 0. Merge splash.cpp 262


typedef String std::wstring;

void CSplashWnd::OnPaint()
{
  ....
  String text = LoadResString(IDS_SPLASH_DEVELOPERS);

  // avoid dereference of empty strings and
  // the NULL termiated character
  if (text.length() >= 0)
  {
  ....
}

UCSniff

V547 Expression '* hDecoder < 0' is always false. Unsigned type value is never < 0. g726_decoder.c 11


int initialize_g726_decoder(unsigned long *hDecoder)
{
  *hDecoder = EasyG726_init_decoder();
  if(*hDecoder<0)
   return -1;
  return 0;
}

Similar errors can be found in some other places:

  • V547 Expression 'currentRTPCall->hDecoderFwd >= 0' is always true. Unsigned type value is always >= 0. ec_siprtp.c 1547
  • V547 Expression 'currentRTPCall->hDecoderRev >= 0' is always true. Unsigned type value is always >= 0. ec_siprtp.c 1550

DeSmuME

V547 Expression 'name[i] >= 0xF0' is always false. The value range of signed char type: [-128, 127]. DeSmuME_VS2005 directory.cpp 118


static int _FAT_directory_lfnLength (const char* name) {
  ....
  for (i = 0; i < nameLength; i++) {
    if (name[i] < 0x20 || name[i] >= ABOVE_UCS_RANGE) {
      return -1;
    }
  }
  ....
}

This is what should have been written here: (unsigned char)(name[i]) >= ABOVE_UCS_RANGE


DeSmuME

V547 Expression 'remain < 0' is always false. Unsigned type value is never < 0. DeSmuME_VS2005 fatfile.cpp 527


static bool _FAT_check_position_for_next_cluster(....,
 size_t remain, ....)
{
  ....
  if ((remain < 0) ||
      (position->sector > partition->sectorsPerCluster)) {
    // invalid arguments - internal error
    r->_errno = EINVAL;
    goto err;
  }
  ....
}

DeSmuME

V547 Expression '(str[0] != ' ') || (str[0] != '\t')' is always true. Probably the '&&' operator should be used here. DeSmuME_VS2005 xstring.cpp 93


int str_ltrim(char *str, int flags) {
  ....
  while (str[0]) {
    if ((str[0] != ' ') || (str[0] != '\t') ||
        (str[0] != '\r') || (str[0] != '\n'))
      break;
  ....
}

DeSmuME

V547 Expression is always true. Probably the '&&' operator should be used here. DeSmuME_VS2005 xstring.cpp 124


int str_rtrim(char *str, int flags) {
 u32 i=0;

 while (strlen(str)) {
  if ((str[strlen(str)-1] != ' ') ||
   (str[strlen(str)-1] != '\t') ||
   (str[strlen(str)-1] != '\r') ||
   (str[strlen(str)-1] != '\n')) break;
  ....
}

DeSmuME

V547 Expression '(char *) cheatsExport->gametitle != ""' is always true. To compare strings you should use strcmp() function. DeSmuME_VS2005 cheatswin.cpp 1382


class CHEATSEXPORT
{
  ....
  u8 *gametitle;
  ....
}

INT_PTR CALLBACK CheatsExportProc(HWND dialog, UINT msg,
                                  WPARAM wparam, LPARAM lparam)
{
  ....
  if ((char*)cheatsExport->gametitle != "")
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'tmp_fat_path != ""' is always true. To compare strings you should use strcmp() function. DeSmuME_VS2005 slot1_config.cpp 56

DeSmuME

V547 Expression 'appliedSize == 'b' && appliedSize == 's'' is always false. Probably the '||' operator should be used here. DeSmuME_VS2005 ram_search.cpp 817


bool Set_RS_Val()
{
  ....
  if((appliedSize == 'b' && appliedSize == 's' &&
      (rs_param < -128 || rs_param > 127)) ||
     (appliedSize == 'b' && appliedSize != 's' &&
      (rs_param < 0 || rs_param > 255)) ||
     (appliedSize == 'w' && appliedSize == 's' &&
      (rs_param < -32768 || rs_param > 32767)) ||
     (appliedSize == 'w' && appliedSize != 's' &&
      (rs_param < 0 || rs_param > 65535)))
    return false;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'appliedSize == 'w' && appliedSize == 's'' is always false. Probably the '||' operator should be used here. DeSmuME_VS2005 ram_search.cpp 819

DeSmuME

V547 Expression 'info.type != 0xFF || info.type != 0xFE' is always true. Probably the '&&' operator should be used here. DeSmuME_VS2005 mc.cpp 1054


void BackupDevice::loadfile()
{
  ....
  if (info.type != 0xFF || info.type != 0xFE)
  ....
}

MAME

V547 Expression is always true. Probably the '&&' operator should be used here. mpu4.c 934


int m_led_extender;
#define CARD_A   1
#define NO_EXTENDER  0

static WRITE8_DEVICE_HANDLER( pia_ic5_porta_w )
{
  ....
  else if ((state->m_led_extender != CARD_A)||
           (state->m_led_extender != NO_EXTENDER))
  ....
}

Trans-Proteomic Pipeline

V547 Expression 'c != '\\' || c != '/'' is always true. Probably the '&&' operator should be used here. Tandem2XML tandemresultsparser.cxx 787


bool TandemResultsParser::writePepXML(....)
{
  ....
  char c = pathSummary.at(pathSummary.length() - 1);
  if (c != '\\' || c != '/')
  ....
}

This is what should have been written here: if (c != '\\' && c != '/')


Trans-Proteomic Pipeline

V547 Expression 'peptideProphetOpts_.find(" PI ", 0) >= 0' is always true. Unsigned type value is always >= 0. pepXMLViewer pipelineanalysis.cxx 1590


class basic_string
{
  ....
  size_type find(const _Elem *_Ptr, size_type _Off = 0) const
  ....
}

void
PipelineAnalysis::prepareFields(void) {
  ....
  if (peptideProphetOpts_.find(" PI ", 0)>=0) {
    fields_.push_back(Field("PpI_zscore"));
  }
  ....
}

This is what should have been written here: (peptideProphetOpts_.find(" PI ", 0) != string::npos).

Similar errors can be found in some other places:

  • V547 Expression 'peptideProphetOpts_.find(" RT ", 0) >= 0' is always true. Unsigned type value is always >= 0. pepXMLViewer pipelineanalysis.cxx 1593

Trans-Proteomic Pipeline

V547 Expression 'numAssignedPeaks >= 0' is always true. Unsigned type value is always >= 0. tpplib spectrastreplicates.cpp 642


void SpectraSTReplicates::aggregateStats(....)
{
  ....
  unsigned int numAssignedPeaks =
    (*r)->entry->getPeakList()->getNumAssignedPeaks();
  if (numAssignedPeaks >= 0)
  {
    sumFracAssigned +=
      (double)numAssignedPeaks / (double)numPeaks;
    numAnnotated++;
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'pl->getNumAssignedPeaks() >= 0' is always true. Unsigned type value is always >= 0. tpplib spectrastreplicates.cpp 724

Trans-Proteomic Pipeline

V547 Expression 'pos < 0' is always false. Unsigned type value is never < 0. dta2mzXML dta2mzxml.cpp 622


int Dta2mzXML::extractScanNum(const string& dtaFileName)
{
  ....
  std::string::size_type pos = dtaFileName.rfind("/");

  if (pos < 0)  {
    pos = dtaFileName.rfind("\\");
  }
  ....
}

This is what should have been written here: (pos == string::npos).

Similar errors can be found in some other places:

  • V547 Expression 'pos < 0' is always false. Unsigned type value is never < 0. dta2mzXML dta2mzxml.cpp 626
  • V547 Expression 'pos < 0' is always false. Unsigned type value is never < 0. dta2mzXML dta2mzxml.cpp 653
  • V547 Expression 'pos < 0' is always false. Unsigned type value is never < 0. dta2mzXML dta2mzxml.cpp 657

Visualization Toolkit (VTK)

V547 Expression is always true. Probably the '&&' operator should be used here. vtkHybrid vtkmniobjectreader.cxx 161


int vtkMNIObjectReader::CanReadFile(const char* fname)
{
  ....
  if (objType == 'P' || objType != 'L' ||
      objType == 'M' || objType != 'F' ||
      objType == 'X' || objType != 'Q' ||
      objType == 'T')
  ....
}

Visualization Toolkit (VTK)

V547 Expression is always true. Probably the '&&' operator should be used here. vtkIO vtknetcdfcfreader.cxx 838


int vtkNetCDFCFReader::RequestDataObject(....)
{
  if (    (preferredDataType != VTK_IMAGE_DATA)
       || (preferredDataType != VTK_RECTILINEAR_GRID) )
  {
    vtkWarningMacro("You have set the OutputType to a data "
                    "type that cannot fully represent the "
                    "topology of the data. Some of the "
                    "topology will be ignored.");
  }
}

Similar errors can be found in some other places:

  • V547 Expression is always true. Probably the '&&' operator should be used here. vtkIO vtknetcdfcfreader.cxx 847

MongoDB

V547 Expression 'str::after("abcde", 'x') == ""' is always false. To compare strings you should use strcmp() function. test.cpp 43


inline const char * after(const char *s, char x);
inline string after(const string& s, char x);
inline const char * after(const char *s, const char *x);
inline string after(string s, string x);

inline const char * after(const char *s, char x) {
  const char *p = strchr(s, x);
  return (p != 0) ? p+1 : "";
}

int main() {
{
  ....
  assert( str::after("abcde", 'x') == "" );
  ....
}

MongoDB

V547 Expression 'i >= 0' is always true. Unsigned type value is always >= 0. mmap_win.cpp 90


void* MemoryMappedFile::map(....) {
  ....
  size_t len = strlen( filename );
  for ( size_t i=len-1; i>=0; i-- ) {
    if ( filename[i] == '/' ||
         filename[i] == '\\' )
      break;

    if ( filename[i] == ':' )
         filename[i] = '_';
  }
  ....
}

CamStudio

V547 Expression 'bytesRead < 0' is always false. Unsigned type value is never < 0. soundfile.cpp 166


bool CSoundFile::OpenWaveFile()
{
  ....
  DWORD bytesRead = mmioRead(m_hFile, (LPSTR)&m_Format,
                             m_MMCKInfoChild.cksize);
  if (bytesRead < 0)
  {
    AfxMessageBox("Error reading PCM wave format record");
    mmioClose(m_hFile,0);
    m_Mode = FILE_ERROR;
    return FALSE;
  }
  ....
}

CamStudio

V547 Expression '* p == 0xFE' is always false. The value range of char type: [127, -128]. compile.cpp 527


#define MAGIC_CONTINUE_NUMBER_LO 0xFE
#define MAGIC_CONTINUE_NUMBER_HI 0x7F

/* I can't believe this actually worked */
void bufferResolveJumps(Buffer out)
{
  ....
  if (*p == MAGIC_CONTINUE_NUMBER_LO &&
      *(p+1) == MAGIC_CONTINUE_NUMBER_HI)
  {
  ....
}

You're right not to believe. It doesn't work indeed! :-)


Samba

V547 Expression '(to != CH_UTF16LE) || (to != CH_UTF16BE)' is always true. Probably the '&&' operator should be used here. charcnv.c 188


static size_t convert_string_internal(....)
{
  ....
    if (((from == CH_UTF16LE)||(from == CH_UTF16BE)) &&
        ((to != CH_UTF16LE)||(to != CH_UTF16BE))) {
  ....
}

Similar errors can be found in some other places:

  • V547 Expression '(to != CH_UTF16LE) || (to != CH_UTF16BE)' is always true. Probably the '&&' operator should be used here. charcnv.c 599

Samba

V547 Expression 'result.pid < 0' is always false. Unsigned type value is never < 0. util.c 2376


struct server_id {
  uint32_t pid;
  uint32_t vnn;
  uint64_t unique_id;
}

struct server_id interpret_pid(const char *pid_string)
{
  struct server_id result;
  ....
  /* Assigning to result.pid may have overflowed
     Map negative pid to -1: i.e. error */
  if (result.pid < 0) {
    result.pid = -1;
  }
  ....
}

Samba

V547 Expression is always false. Consider reviewing this expression. pdbtest.c 170


static bool samu_correct(struct samu *s1, struct samu *s2)
{
  ....
  if (d2_buf == NULL && d2_buf != NULL) {
    DEBUG(0, ("Logon hours is not set\n"));
    ret = False;
  }
  ....
}

Tor

V547 Expression is always true. Probably the '&&' operator should be used here. transports.c 556


void
pt_configure_remaining_proxies(void)
{
  ....
  tor_assert(mp->conf_state != PT_PROTO_BROKEN ||
             mp->conf_state != PT_PROTO_FAILED_LAUNCH);
  ....
}

OpenCV

V547 Expression 'd > maxd' is always false. Unsigned type value is never < 0. fuzzymeanshifttracker.cpp 386


void CvFuzzyMeanShiftTracker::SearchWindow::initDepthValues(....)
{
  unsigned int d=0, mind = 0xFFFF, maxd = 0,
           m0 = 0, m1 = 0, mc, dd;
  ....
  for (int j = 0; j < height; j++)
  {
    ....
    if (d > maxd)
      maxd = d;
    ....
  }
}

Variable 'd' does not change in the loop.


ReactOS

V547 Expression 'i < 0x10000' is always true. The value range of unsigned short type: [0, 65535]. xboxhw.c 358


#define DISKREADBUFFER_SIZE HEX(10000)

typedef unsigned short USHORT, *PUSHORT;

static VOID DetectBiosDisks(....)
{
  USHORT i;
  ....
  Changed = FALSE;
  for (i = 0; ! Changed && i < DISKREADBUFFER_SIZE; i++)
  {
    Changed = ((PUCHAR)DISKREADBUFFER)[i] != 0xcd;
  }
  ....
}

ReactOS

V547 Expression 'ads->udpsocket < 0' is always false. Unsigned type value is never < 0. setup.c 539


typedef UINT_PTR SOCKET;
#define ADNS_SOCKET SOCKET

struct adns__state {
  ....
  ADNS_SOCKET udpsocket, tcpsocket;
  ....
};

static int init_finish(adns_state ads) {
  ....
  if (ads->udpsocket<0) { r= errno; goto x_free; }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'fd < 0' is always false. Unsigned type value is never < 0. event.c 117
  • V547 Expression 'ads->udpsocket >= 0' is always true. Unsigned type value is always >= 0. check.c 105
  • V547 Expression 'ads->tcpsocket >= 0' is always true. Unsigned type value is always >= 0. check.c 114
  • And 1 additional diagnostic messages.

ReactOS

V547 Expression '0 <= Id' is always true. Unsigned type value is always >= 0. menu.c 2663


static INT FASTCALL
MenuButtonUp(MTRACKER *Mt, HMENU PtMenu, UINT Flags)
{
  UINT Id;
  ....
  Id = NtUserMenuItemFromPoint(....);
  ....
  if (0 <= Id &&
      MenuGetRosMenuItemInfo(MenuInfo.Self, Id, &ItemInfo) &&
      MenuInfo.FocusedItem == Id)
  ....
}

ReactOS

V547 Expression 'Info->nPage < 0' is always false. Unsigned type value is never < 0. scrollbar.c 428


typedef struct tagSCROLLINFO {
  ....
  UINT nPage;
  ....
} SCROLLINFO,*LPSCROLLINFO;

static DWORD FASTCALL
co_IntSetScrollInfo(....)
{
  LPSCROLLINFO Info;
  ....
  /* Make sure the page size is valid */
  if (Info->nPage < 0)
  {
    pSBData->page = Info->nPage = 0;
  }
  ....
}

ReactOS

V547 Expression 'Entry->Id <= 0xffff' is always true. The value range of unsigned short type: [0, 65535]. res.c 312


typedef unsigned short WORD;
WORD Id;

static LONG
LdrpCompareResourceNames_U(....)
{
  /* Fail if ResourceName2 is an ID */
  if (Entry->Id <= USHRT_MAX) return -1;
  ....
}

ReactOS

V547 Expression 'index < 0' is always false. Unsigned type value is never < 0. extensions.c 936


typedef unsigned int GLuint;

const GLubyte *_mesa_get_enabled_extension(
  struct gl_context *ctx, GLuint index)
{
  const GLboolean *base;
  size_t n;
  const struct extension *i;
  if (index < 0)
    return NULL;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'ch <= 0xFF' is always true. The value range of char type: [-128, 127]. hexedit.c 1279
  • V547 Expression 'index >= 0' is always true. Unsigned type value is always >= 0. st_glsl_to_tgsi.cpp 4013
  • V547 Expression 'index >= 0' is always true. Unsigned type value is always >= 0. st_glsl_to_tgsi.cpp 4023
  • And 4 additional diagnostic messages.

Windows 8 Driver Samples

V547 Expression 'i < 256' is always true. The value range of unsigned char type: [0, 255]. hw_mac.c 1946


VOID HwFillRateElement(....)
{
  UCHAR i, j;
  ....
  for (i = 0; (i < basicRateSet->uRateSetLength) &&
              (i < 256); i++)
  {
    rate[i] = 0x80 | basicRateSet->ucRateSet[i];
  }
  ....
}

Windows 8 Driver Samples

V547 Expression is always false. The value range of unsigned char type: [0, 255]. hw_mac.c 1971


VOID HwFillRateElement(....)
{
  ....
  UCHAR rate[256];
  UCHAR rateNum;
  ....
  if (rateNum == sizeof(rate) / sizeof(UCHAR))
    break;
  ....
}

NetXMS

V547 Expression 'sockfd < 0' is always false. Unsigned type value is never < 0. radius.cpp 682


typedef UINT_PTR SOCKET;

static int DoRadiusAuth(....)
{
  SOCKET sockfd;
  ....
  // Open a socket.
  sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  if (sockfd < 0)
  {
    DbgPrintf(3, _T("RADIUS: Cannot create socket"));
    pairfree(req);
    return 5;
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'col->fd >= 0' is always true. Unsigned type value is always >= 0. ipfix.c 845
  • V547 Expression is always false. Unsigned type value is never < 0. ipfix.c 962
  • V547 Expression 'sock < 0' is always false. Unsigned type value is never < 0. ipfix.c 1013
  • And 4 additional diagnostic messages.

NetXMS

V547 Expression 'i >= 0' is always true. Unsigned type value is always >= 0. ipfix.c 488


int ipfix_snprint_string(....)
{
  size_t  i;
  uint8_t *in = (uint8_t*) data;

  for( i=len-1; i>=0; i-- ) {
    if ( in[i] == '\0' ) {
      return snprintf( str, size, "%s", in );
    }
  }
  ....
}

NetXMS

V547 Expression 'value >= 0' is always true. Unsigned type value is always >= 0. catalyst.cpp 71


bool CatalystDriver::isDeviceSupported(
  SNMP_Transport *snmp, const TCHAR *oid)
{
  DWORD value = 0;
  if (SnmpGet(snmp->getSnmpVersion(), snmp,
             _T(".1.3.6.1.4.1.9.5.1.2.14.0"),
             NULL, 0, &value, sizeof(DWORD), 0)
      != SNMP_ERR_SUCCESS)
    return false;
  // Catalyst 3550 can return 0 as number of slots
  return value >= 0;
}

WinMerge

V547 Expression 'i >= 0' is always true. Unsigned type value is always >= 0. mergedoclinediffs.cpp 282


void CMergeDoc::Computelinediff(....)
{
  ....
  vector<wdiff*>::size_type i;
  ....
  for (i=worddiffs.size() - 1; i>=0; --i)
  {
    const wdiff * diff = worddiffs[i];
    if (end1 == -1 && diff->end[0] != -1)
      end1 = diff->end[0];
    if (end2 == -1 && diff->end[1] != -1)
      end2 = diff->end[1];
    if (end1 != -1 && end2 != -1)
      break; // found both
  }
  ....
}

QuickThread

V547 Expression 'NUMA_NodeNumber >= 0' is always true. Unsigned type value is always >= 0. quickthreadnuma.cpp 101


int numa_preferred(void)
{
  unsigned char NUMA_NodeNumber = numa_available();
  if(NUMA_NodeNumber >= 0)
    return NUMA_NodeNumber;
  return 0;
}

TortoiseSVN

V547 Expression 'ticks < 0' is always false. Unsigned type value is never < 0. winplink.c 635


int main(int argc, char **argv)
{
  ....
  DWORD ticks;
  ....
  if (run_timers(now, &next)) {
    ticks = next - GETTICKCOUNT();
    if (ticks < 0) ticks = 0;
  } else {
    ticks = INFINITE;
  }
  ....
}

Chromium

V547 Expression 'socket_ < 0' is always false. Unsigned type value is never < 0. tcp_server_socket_win.cc 48


typedef UINT_PTR SOCKET;

SOCKET socket_;

int TCPServerSocketWin::Listen(....) {
  ....
  socket_ = socket(address.GetSockAddrFamily(),
                   SOCK_STREAM, IPPROTO_TCP);
  if (socket_ < 0) {
    PLOG(ERROR) << "socket() returned an error";
    return MapSystemError(WSAGetLastError());
  }
  ....
}

Multi Theft Auto

V547 Expression 'm_TidyupTimer.Get() < 0' is always false. Unsigned type value is never < 0. crenderitem.effectcloner.cpp 182


unsigned long long Get ( void );

void CEffectClonerImpl::MaybeTidyUp ( void )
{
  ....
  if ( m_TidyupTimer.Get () < 0 )
    return;
  ....
}

Multi Theft Auto

V547 Expression 'ucNumber >= 1000' is always false. The value range of unsigned char type: [0, 255]. cluafunctiondefinitions.cpp 4450


int CLuaFunctionDefinitions::GetVehicleUpgradeSlotName (....)
{
  unsigned char ucNumber;
  ....
  else if ( ucNumber >= 1000 && ucNumber <= 1193 )
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'ucNumber <= 1193' is always true. The value range of unsigned char type: [0, 255]. cluafunctiondefinitions.cpp 4450
  • V547 Expression 'ucNameLength > 1024' is always false. The value range of unsigned char type: [0, 255]. cpackethandler.cpp 2766

Multi Theft Auto

V547 Expression 'uiResourceLength < 0' is always false. Unsigned type value is never < 0. csettings.cpp 408


inline const char* CSettings::GetName (....,
  unsigned int uiResourceLength )
{
  // Only calculate the resource length if it's
  // not already specified
  if ( uiResourceLength < 0 ) {
    ....
  } else {
    ....
  }
}

Similar errors can be found in some other places:

  • V547 Expression 'pVehicle->GetVehicleSirenCount() >= 0' is always true. Unsigned type value is always >= 0. cmultiplayersa_1.3.cpp 376
  • V547 Expression 'sirenData.data.m_ucSirenCount >= 0' is always true. Unsigned type value is always >= 0. cvehiclerpcs.cpp 604

Multi Theft Auto

V547 Expression 'wc < 0x10000' is always true. The value range of wchar_t type: [0, 65535]. utf8.h 121


int
utf8_wctomb (unsigned char *dest, wchar_t wc, int dest_size)
{
  if (!dest)
    return 0;
  int count;
  if (wc < 0x80)
    count = 1;
  else if (wc < 0x800)
    count = 2;
  else if (wc < 0x10000)
    count = 3;
  else if (wc < 0x200000)
    count = 4;
  else if (wc < 0x4000000)
    count = 5;
  else if (wc <= 0x7fffffff)
    count = 6;
  else
    return RET_ILSEQ;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'wc < 0x200000' is always true. The value range of wchar_t type: [0, 65535]. utf8.h 123
  • V547 Expression 'wc < 0x4000000' is always true. The value range of wchar_t type: [0, 65535]. utf8.h 125
  • V547 Expression 'wc <= 0x7fffffff' is always true. The value range of wchar_t type: [0, 65535]. utf8.h 127

Boost (C++ libraries)

V547 Expression 'new_socket.get() >= 0' is always true. Unsigned type value is always >= 0. win_iocp_socket_service.hpp 436


typedef SOCKET socket_type;

class socket_holder
{
  ....
  socket_type socket_;
  ....
  socket_type get() const { return socket_; }
  ....
};

template <typename Socket>
boost::system::error_code accept(....)
{
  ....
  // On success, assign new connection to peer socket object.
  if (new_socketnew_socket.get() >= 0)
  {
    if (peer_endpoint)
      peer_endpoint->resize(addr_len);
    if (!peer.assign(impl.protocol_, new_socket.get(), ec))
      new_socket.release();
  }
  return ec;
}

Trans-Proteomic Pipeline

V547 Expression 'b + tau >= 0' is always true. Unsigned type value is always >= 0. spectrastpeaklist.cpp 2058


double SpectraSTPeakList::calcXCorr() {
  ....
  for (int tau = -75; tau <= 75; tau++) {

    float dot = 0.0;
    for (unsigned int b = 0; b < numBins; b++) {
      if (b + tau >= 0 && b + tau < (int)numBins) {
        dot += (*m_bins)[b] * theoBins[b + tau] / 10000.0;
      }
    }
    ....
  ....
}

TinyCAD

V547 Expression 'parentPos >= 0' is always true. Unsigned type value is always >= 0. bomgenerator.cpp 77


void CBOMGenerator::GenerateBomForDesign(
  int level, size_t parentPos, ....)
{
  ....
  if (parentPos >= 0) cmrParent = cmrDefaultParent;
  ....
}

SeqAn

V547 Expression 'pos < 0' is always false. Unsigned type value is never < 0. tokenize.h 1548


template <typename TStream, typename TPass, typename TBuffer>
inline int
readLineStripTrailingBlanks(TBuffer & buffer,
  RecordReader<TStream, TPass> & reader)
{
  ....
  typename Size<TBuffer>::Type pos = length(buffer) - 1;

  if (pos < 0)
    return 0;
  ....
}

CrashRpt library

V547 Expression 'pos < 0' is always false. Unsigned type value is never < 0. main.cpp 314


typedef std::basic_string<TCHAR> tstring;

int process_report(....)
{
  ....
  tstring sInDirName;
  ....
  size_t pos = sInDirName.rfind('\\');
  if(pos<0) // There is no back slash in path
  {
    sInDirName = _T("");
    sInFileName = szInput;
  }
  else
  {
    sInFileName = sInDirName.substr(pos+1);
    sInDirName = sInDirName.substr(0, pos);
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'pos < 0' is always false. Unsigned type value is never < 0. main.cpp 352
  • V547 Expression 'pos >= 0' is always true. Unsigned type value is always >= 0. main.cpp 837
  • V547 Expression 'pos >= 0' is always true. Unsigned type value is always >= 0. minidumpreader.cpp 775

WebPagetest

V547 Expression is always false. Probably the '||' operator should be used here. json_reader.cpp 566


bool
Reader::readArray( Token &tokenStart )
{
  ....
  bool badTokenType = ( token.type_ == tokenArraySeparator &&
                        token.type_ == tokenArrayEnd );
  if ( !ok  ||  badTokenType )
  {
    ....
}

This is what should have been written here: token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd


Snes9x

V547 Expression is always false. Probably the '||' operator should be used here. ram_search.cpp 921


bool Set_RS_Val()
{
  ....
  int appliedSize;
  ....
  if((appliedSize == TEXT('b') && appliedSize == TEXT('s') &&
      (rs_param < -128 || rs_param > 127)) ||
     (appliedSize == TEXT('b') && appliedSize != TEXT('s') &&
      (rs_param < 0 || rs_param > 255)) ||
     (appliedSize == TEXT('w') && appliedSize == TEXT('s') &&
      (rs_param < -32768 || rs_param > 32767)) ||
     (appliedSize == TEXT('w') && appliedSize != TEXT('s') &&
      (rs_param < 0 || rs_param > 65535)))
     return false;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression is always false. Probably the '||' operator should be used here. ram_search.cpp 923

VirtualDub

V547 Expression 'res < 0' is always false. Unsigned type value is never < 0. Riza w32videocodecpack.cpp 828


void VDVideoCompressorVCM::GetState(vdfastvector<uint8>& data) {
  DWORD res;
  ....
  res = ICGetState(hic, data.data(), size);
  ....
  if (res < 0)
    throw MyICError("Video compression", res);
}

Similar errors can be found in some other places:

  • V547 Expression 'retval < 0' is always false. Unsigned type value is never < 0. Riza w32videocodec.cpp 284

Prime95

V547 Expression '* p == '//'' is always false. The value range of char type: [-128, 127]. prime95 prime95.cpp 156


BOOL CPrime95App::InitInstance()
{
  char *p;
  ....
  for (p = m_lpCmdLine; *p == '//' || *p == '-'; ) {
  ....
}

Prime95

V547 Expression '(s = socket(hp->h_addrtype, 1, 0)) < 0' is always false. Unsigned type value is never < 0. prime95 primenet.c 354


typedef UINT_PTR SOCKET;

SOCKET socket(__in int af, __in int type,
              __in int protocol);

int pnHttpServer (char *pbuf, unsigned cbuf, char* postargs)
{
  ....
  if ((s = socket (hp->h_addrtype, SOCK_STREAM, 0)) < 0) {
  ....
}

Geant4 software

V547 Expression is always true. Probably the '&&' operator should be used here. G4had_im_r_matrix g4collisionmesonbaryonelastic.cc 53


G4bool G4CollisionMesonBaryonElastic::
 IsInCharge(const G4KineticTrack& trk1,
            const G4KineticTrack& trk2) const
 {
   G4bool result = false;
   G4ParticleDefinition * p1 = trk1.GetDefinition();
   G4ParticleDefinition * p2 = trk2.GetDefinition();
   if(   (GetNumberOfPartons(p1) != 2 ||
          GetNumberOfPartons(p2) != 3)
       ||(GetNumberOfPartons(p1) != 3 ||
          GetNumberOfPartons(p2) != 2) )
   {
     result = false;
   }
  ....
}

libusbx

V547 Expression '0 > * busnum' is always false. Unsigned type value is never < 0. linux_usbfs.c 620


int linux_get_device_address (....,
  uint8_t *busnum, uint8_t *devaddr,
  ....)
{
  ....
  *busnum = __read_sysfs_attr(ctx, sys_name, "busnum");
  if (0 > *busnum)
    return *busnum;

  *devaddr = __read_sysfs_attr(ctx, sys_name, "devnum");
  if (0 > *devaddr)
    return *devaddr;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression '0 > * devaddr' is always false. Unsigned type value is never < 0. linux_usbfs.c 624

PostgreSQL Database Management System

V547 Expression 'sock_fd < 0' is always false. Unsigned type value is never < 0. postgres auth.c 1668


typedef UINT_PTR SOCKET;
typedef SOCKET pgsocket;

static int
ident_inet(hbaPort *port)
{
  ....
  pgsocket  sock_fd;
  ....
  sock_fd = socket(ident_serv->ai_family,
                   ident_serv->ai_socktype,
                   ident_serv->ai_protocol);
  if (sock_fd < 0)
  {
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'sock_fd >= 0' is always true. Unsigned type value is always >= 0. postgres auth.c 1748
  • V547 Expression 'sock < 0' is always false. Unsigned type value is never < 0. postgres auth.c 2567
  • V547 Expression is always false. Unsigned type value is never < 0. postgres pqcomm.c 395
  • And 2 additional diagnostic messages.

Source Engine SDK

V547 Expression 'm_nActiveParticles >= 0' is always true. Unsigned type value is always >= 0. Client (HL2) particlemgr.cpp 967


unsigned short m_nActiveParticles;

void CParticleEffectBinding::RemoveParticle(
  Particle *pParticle )
{
  ....
  Assert( m_nActiveParticles >= 0 );
  ....
}

Source Engine SDK

V547 Expression 'firstedge >= 0' is always true. Unsigned type value is always >= 0. Vbsp writebsp.cpp 1428


static void AddNodeToBounds(....)
{
  ....
  unsigned int firstedge = dfaces[face].firstedge;
  Assert( firstedge >= 0 );
  ....
}

Source Engine SDK

V547 Expression 'pEdge->v[0] >= 0' is always true. Unsigned type value is always >= 0. Vbsp writebsp.cpp 1435


struct dedge_t
{
  DECLARE_BYTESWAP_DATADESC();
  unsigned short  v[2];
};

static void AddNodeToBounds(....)
{
  ....
  Assert( pEdge->v[0] >= 0 );
  Assert( pEdge->v[1] >= 0 );
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'pEdge->v[1] >= 0' is always true. Unsigned type value is always >= 0. Vbsp writebsp.cpp 1436

Source Engine SDK

V547 Expression 'numbounce < 0' is always false. Unsigned type value is never < 0. Vrad_dll vrad.cpp 2412


unsigned  numbounce = 100;

int ParseCommandLine( int argc, char **argv, bool *onlydetail )
{
  ....
  numbounce = atoi (argv[i]);
  if ( numbounce < 0 )
  {
    Warning(
      "Error: expected non-negative value after '-bounce'\n");
    return 1;
  }
  ....
}

Firebird

V547 Expression '-- i >= 0' is always true. Unsigned type value is always >= 0. isql.cpp 3421


static processing_state add_row(TEXT* tabname)
{
  ....
  unsigned i = n_cols;
  while (--i >= 0)
  {
    if (colnumber[i] == ~0u)
  {
       bldr->remove(fbStatus, i);
       if (ISQL_errmsg(fbStatus))
         return (SKIP);
    }
  }
  msg.assignRefNoIncr(bldr->getMetadata(fbStatus));
  ....
}

Firebird

V547 Expression 'scale < 0' is always false. Unsigned type value is never < 0. isql.cpp 3716


static processing_state add_row(TEXT* tabname)
{
  ....
  unsigned varLength, scale;
  ....
  scale = msg->getScale(fbStatus, i);
  ....
  if (scale < 0)
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'scale < 0' is always false. Unsigned type value is never < 0. isql.cpp 4437

Firebird

V547 Expression '* * argv != 'n' || * * argv != 'N'' is always true. Probably the '&&' operator should be used here. gpre.cpp 1829


static bool get_switches(....)
  ....
  if (**argv != 'n' || **argv != 'N')
  {
    fprintf(stderr,
      "-sqlda :  Deprecated Feature: you must use XSQLDA\n ");
    print_switches();
    return false;
  }
  ....
}

CryEngine 3 SDK

V547 Expression is always true. Probably the '&&' operator should be used here. searchmodule.cpp 469


SearchSpotStatus GetStatus() const { return m_status; }

SearchSpot* SearchGroup::FindBestSearchSpot(....)
{
  ....
  if(searchSpot.GetStatus() != Unreachable ||
     searchSpot.GetStatus() != BeingSearchedRightAboutNow)
  ....
}

CryEngine 3 SDK

V547 Expression 'inTimelineId >= 0' is always true. Unsigned type value is always >= 0. circularstatsstorage.cpp 31


const CCircularBufferTimeline *
CCircularBufferStatsContainer::GetTimeline(
  size_t inTimelineId) const
{
  ....
  if (inTimelineId >= 0 && (int)inTimelineId < m_numTimelines)
  {
    tl = &m_timelines[inTimelineId];
  }
  else
  {
    CryWarning(VALIDATOR_MODULE_GAME,VALIDATOR_ERROR,
               "Statistics event %" PRISIZE_T
               " is larger than the max registered of %"
               PRISIZE_T ", event ignored",
               inTimelineId,m_numTimelines);
  }
  ....
}

ICU

V547 Expression 'standardDate.wDay < 0' is always false. Unsigned type value is never < 0. wintzimpl.cpp 66


int32_t getRuleWeekInMonth(void) const;

typedef struct _SYSTEMTIME {
  ....
  WORD wDay;
  ....
} SYSTEMTIME, *PSYSTEMTIME;

static UBool getSystemTimeInformation(....)
{
  ....
  standardDate.wDay = std->getRule()->getRuleWeekInMonth();
  if (standardDate.wDay < 0) {
    standardDate.wDay = 5;
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'daylightDate.wDay < 0' is always false. Unsigned type value is never < 0. wintzimpl.cpp 87

Scilab

V547 Expression 'iParentType == 9 && iParentType == 21' is always false. Probably the '||' operator should be used here. sci_uimenu.c 99


#define __GO_FIGURE__ 9
#define __GO_UIMENU__ 21

int sci_uimenu(char *fname, unsigned long fname_len)
{
  ....
  if (iParentType == __GO_FIGURE__ &&
      iParentType == __GO_UIMENU__)
  {
    Scierror(999, _("%s: Wrong type for input argument #%d: ")
             _("A '%s' or '%s' handle expected.\n"),
             fname, 1, "Figure", "Uimenu");
    return FALSE;
  }
  ....
}

This is what should have been written here: iParentType != __GO_FIGURE__ && iParentType != __GO_UIMENU__


Word for Windows 1.1a

V547 Expression '-- cch >= 0' is always true. Unsigned type value is always >= 0. mergeelx.c 1188


void GetNameElk(elk, stOut)
ELK elk;
unsigned char *stOut;
{
  unsigned char *stElk = &rgchElkNames[mpelkichName[elk]];
  unsigned cch = stElk[0] + 1;

  while (--cch >= 0)
    *stOut++ = *stElk++;
}

Qt

V547 Expression is always true. Probably the '&&' operator should be used here. qsgatlastexture.cpp 271


void Atlas::uploadBgra(Texture *texture)
{
  const QRect &r = texture->atlasSubRect();
  QImage image = texture->image();

  if (image.format() != QImage::Format_ARGB32_Premultiplied ||
      image.format() != QImage::Format_RGB32) {
  ....
}

CLucene

V547 Expression '-- size >= 0' is always true. Unsigned type value is always >= 0. arrays.h 154


class Arrays
{
  ....
   bool equals( class1* val1, class2* val2 ) const{
     static _comparator comp;
     if ( val1 == val2 )
       return true;
     size_t size = val1->size();
     if ( size != val2->size() )
       return false;
     _itr1 itr1 = val1->begin();
     _itr2 itr2 = val2->begin();
     while ( --size >= 0 ){
       if ( !comp(*itr1,*itr2) )
         return false;
       itr1++;
       itr2++;
     }
   return true;
  }
  ....
}

CLucene

V547 Expression 'q->getQueryName() != L"BooleanQuery"' is always true. To compare strings you should use wcscmp() function. multifieldqueryparser.cpp 44


const TCHAR* getQueryName() const;

Query* MultiFieldQueryParser::parse(....)
{
  ....
  Query* q = QueryParser::parse(query, fields[i], analyzer);
  if (q && (q->getQueryName() != _T("BooleanQuery")
      || ((BooleanQuery*)q)->getClauseCount() > 0)) {
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'q->getQueryName() != L"BooleanQuery"' is always true. To compare strings you should use wcscmp() function. multifieldqueryparser.cpp 63

TortoiseGit

V547 Expression is always false. Probably the '||' operator should be used here. clonedlg.cpp 413


void CCloneDlg::OnBnClickedCheckSvn()
{
  ....
  CString str;
  m_URLCombo.GetWindowText(str);

  while(str.GetLength()>=1 &&
        str[str.GetLength()-1] == _T('\\') &&
        str[str.GetLength()-1] == _T('/'))
  {
    str=str.Left(str.GetLength()-1);
  }
  ....
}

TortoiseGit

V547 Expression is always true. Probably the '&&' operator should be used here. smart_protocol.c 264


enum git_ack_status {
  GIT_ACK_NONE,
  GIT_ACK_CONTINUE,
  GIT_ACK_COMMON,
  GIT_ACK_READY
};

static int wait_while_ack(gitno_buffer *buf)
{
  ....
  if (pkt->type == GIT_PKT_ACK &&
      (pkt->status != GIT_ACK_CONTINUE ||
       pkt->status != GIT_ACK_COMMON)) {
  ....
}

Tesseract

V547 Expression 'c == 'x' && c == 'X'' is always false. Probably the '||' operator should be used here. libtesseract303 scanutils.cpp 135


uintmax_t streamtoumax(FILE* s, int base) {
  int d, c = 0;
  ....
  c = fgetc(s);
  if (c == 'x' && c == 'X') c = fgetc(s);
  ....
}

WebRTC

V547 Expression 'new_fd < 0' is always false. Unsigned type value is never < 0. ccsip_platform_tcp.c 438


typedef UINT_PTR SOCKET;
typedef SOCKET cpr_socket_t;

cpr_socket_t
sip_tcp_create_connection (sipSPIMessage_t *spi_msg)
{
  cpr_socket_t new_fd;
  ....
  new_fd = cprSocket(af_listen, SOCK_STREAM, 0);
  if (new_fd < 0) {
    CCSIP_DEBUG_ERROR(SIP_F_PREFIX"Socket creation failed %d.",
                      fname, cpr_errno);
    return INVALID_SOCKET;
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'sock < 0' is always false. Unsigned type value is never < 0. ccsip_platform_tls.c 118

Mozilla Firefox

V547 Expression 'aChannelCount < 0' is always false. Unsigned type value is never < 0. adts.cpp 44


bool
Adts::ConvertEsdsToAdts(uint16_t aChannelCount, ....)
{
  ....
  if (newSize >= (1 << 13) || aChannelCount < 0 ||
      aChannelCount > 15 || aFrequencyIndex < 0 ||
      aProfile < 1 || aProfile > 4)
    return false;
  ....
}

Mozilla Firefox

V547 Expression is always false. Probably the '||' operator should be used here. nswindowsregkey.cpp 292


NS_IMETHODIMP
nsWindowsRegKey::ReadStringValue(....)
{
  ....
  DWORD type;
  ....
  if (type != REG_SZ && type == REG_EXPAND_SZ &&
      type == REG_MULTI_SZ)
    return NS_ERROR_FAILURE;
  ....
}

Mozilla Firefox

V547 Expression '-- guess >= minEntry' is always true. Unsigned type value is always >= 0. ion.cpp 1112


const SafepointIndex *
IonScript::getSafepointIndex(uint32_t disp) const
{
  ....
  size_t minEntry = 0;
  ....
  size_t guess = ....;
  ....
  while (--guess >= minEntry) {
    guessDisp = table[guess].displacement();
    JS_ASSERT(guessDisp >= disp);
    if (guessDisp == disp)
      return &table[guess];
  }
  ....
}

Newton Game Dynamics

V547 Expression 'm_mantissa[0] >= 0' is always true. Unsigned type value is always >= 0. dggoogol.cpp 55


typedef unsigned long long dgUnsigned64;

dgUnsigned64 m_mantissa[DG_GOOGOL_SIZE];

dgGoogol::dgGoogol(dgFloat64 value)
  :m_sign(0)
  ,m_exponent(0)
{
  ....
  m_mantissa[0] = (dgInt64 (dgFloat64 (
                    dgUnsigned64(1)<<62) * mantissa));

  // it looks like GCC have problems with this
  dgAssert (m_mantissa[0] >= 0);
  ....
}

Cocos2d-x

V547 Expression '0 == commonInfo->eventName' is always false. Pointer 'commonInfo->eventName' != NULL. ccluaengine.cpp 436


struct CommonScriptData
{
  // Now this struct is only used in LuaBinding.
  int handler;
  char eventName[64];
  ....
};

int LuaEngine::handleCommonEvent(void* data)
{
  ....
  CommonScriptData* commonInfo = static_cast<....*>(data);
  if (NULL == commonInfo->eventName ||                   // <=
      0 == commonInfo->handler)
    return 0;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression '0 != commonInfo->eventSourceClassName' is always true. Pointer 'commonInfo->eventSourceClassName' != NULL. ccluaengine.cpp 442

Asterisk

V547 Expression is always false. Unsigned type value is never < 0. enum.c 309


static int ebl_callback(....)
{
  unsigned int i;
  ....
  if ((i = dn_expand((unsigned char *)fullanswer,
     (unsigned char *)answer + len,
     (unsigned char *)answer, c->apex, sizeof(c->apex) - 1)) < 0)
  {
    ast_log(LOG_WARNING, "Failed to expand hostname\n");
    return 0;
  }
}

PHP:Hypertext Preprocessor

V547 Expression 'tmp_len >= 0' is always true. Unsigned type value is always >= 0. ftp_fopen_wrapper.c 639


static size_t php_ftp_dirstream_read(....)
{
  size_t tmp_len;
  ....
  /* Trim off trailing whitespace characters */
  tmp_len--;
  while (tmp_len >= 0 &&                  // <=
    (ent->d_name[tmp_len] == '\n' ||
     ent->d_name[tmp_len] == '\r' ||
     ent->d_name[tmp_len] == '\t' ||
     ent->d_name[tmp_len] == ' ')) {
       ent->d_name[tmp_len--] = '\0';
  }
  ....
}

Oracle VM Virtual Box

V547 Expression is always true. Probably the '&&' operator should be used here. vboxfboverlay.cpp 2259


VBoxVHWAImage::reset(VHWACommandList * pCmdList)
{
  ....
  if (pCmd->SurfInfo.PixelFormat.c.rgbBitCount != 32
   || pCmd->SurfInfo.PixelFormat.c.rgbBitCount != 24)
  {
    AssertFailed();
    pCmd->u.out.ErrInfo = -1;
    return VINF_SUCCESS;
  }
  ....
}

K Desktop Environment

V547 Expression is always true. Probably the '&&' operator should be used here. incidenceformatter.cpp 2684


static QString formatICalInvitationHelper(....)
{
  ....
  a = findDelegatedFromMyAttendee( inc );
  if ( a ) {
    if ( a->status() != Attendee::Accepted ||
         a->status() != Attendee::Tentative ) {
      html += responseButtons( inc, rsvpReq, rsvpRec, helper );
      break;
    }
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression is always true. Probably the '&&' operator should be used here. incidenceformatter.cpp 3293

Miranda NG

V547 Expression 'dis->itemData >= 0' is always true. Unsigned type value is always >= 0. TabSRMM hotkeyhandler.cpp 213


ULONG_PTR itemData;

LONG_PTR CALLBACK HotkeyHandlerDlgProc(....)
{
  ....
  if (dis->itemData >= 0) {
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'wParam >= 0' is always true. Unsigned type value is always >= 0. Jabber jabber_agent.cpp 58
  • V547 Expression 'ft->std.currentFileSize < 0' is always false. Unsigned type value is never < 0. Jabber jabber_file.cpp 76
  • V547 Expression 'lpdis->itemID < 0' is always false. Unsigned type value is never < 0. Jabber jabber_groupchat.cpp 522
  • And 24 additional diagnostic messages.

Miranda NG

V547 Expression 'cp != "\005"' is always true. To compare strings you should use strcmp() function. Yahoo libyahoo2.cpp 4486


static void yahoo_process_search_connection(....)
{
  ....
  if (cp != "\005")
  ....
}

Miranda NG

V547 Expression 'i >= 0' is always true. Unsigned type value is always >= 0. Tipper str_utils.cpp 220


TCHAR *myfgets(TCHAR *Buf, int MaxCount, FILE *File)
{
  _fgetts(Buf, MaxCount, File);
  for (size_t i = _tcslen(Buf) - 1; i >= 0; i--)
  {
    if (Buf[i] == '\n' || Buf[i] == ' ')
      Buf[i] = 0;
    else
      break;
  }

  CharLower(Buf);
  return Buf;
}

LibreOffice

V547 Expression is always true. Probably the '&&' operator should be used here. sbxmod.cxx 1777


enum SbxDataType {
  SbxEMPTY    =  0,
  SbxNULL     =  1,
  ....
};

void SbModule::GetCodeCompleteDataFromParse(
  CodeCompleteDataCache& aCache)
{
  ....
  if( (pSymDef->GetType() != SbxEMPTY) ||
      (pSymDef->GetType() != SbxNULL) )
    aCache.InsertGlobalVar( pSymDef->GetName(),
      pParser->aGblStrings.Find(pSymDef->GetTypeId()) );
  ....
}

Similar errors can be found in some other places:

  • V547 Expression is always true. Probably the '&&' operator should be used here. sbxmod.cxx 1785

LibreOffice

V547 Expression is always false. Probably the '||' operator should be used here. svdobj.cxx 2352


enum SfxStyleFamily {
  ....
  SFX_STYLE_FAMILY_PARA = 2,
  ....
  SFX_STYLE_FAMILY_PAGE = 8,
  ....
};

void SdrObject::NbcSetStyleSheet(SfxStyleSheet* pNewStyleSheet,
                                 bool bDontRemoveHardAttr)
{
  // only allow graphic and presentation styles for shapes
  if( pNewStyleSheet &&
     (pNewStyleSheet->GetFamily() == SFX_STYLE_FAMILY_PARA) &&
     (pNewStyleSheet->GetFamily() == SFX_STYLE_FAMILY_PAGE) )
        return;

    GetProperties().SetStyleSheet(pNewStyleSheet,
                                  bDontRemoveHardAttr);
}

LibreOffice

V547 Expression is always false. Probably the '||' operator should be used here. xmlstylesexporthelper.cxx 223


OUString ScMyValidationsContainer::GetCondition(
  ScXMLExport& rExport, const ScMyValidation& aValidation)
{
  ....
  if (.... ||
      (aValidation.aOperator ==
                          sheet::ConditionOperator_BETWEEN &&
       aValidation.aOperator ==
                          sheet::ConditionOperator_NOT_BETWEEN &&
       !aValidation.sFormula2.isEmpty())))
  ....
}

.NET CoreCLR

V547 Expression 'maxCpuId >= 0' is always true. Unsigned type value is always >= 0. cee_wks codeman.cpp 1219


void EEJitManager::SetCpuInfo()
{
  ....
  unsigned char buffer[16];
  DWORD maxCpuId = getcpuid(0, buffer);
  if (maxCpuId >= 0)
  {
  ....
}

Haiku Operation System

V547 Expression '* r && * r == ' ' && * r == '\t'' is always false. Probably the '||' operator should be used here. selection.c 546


static int
selection_rel(....)
{
  char *r, *rname;
  ....
  while (*r && *r == ' ' && *r == '\t')
    r++;
  ....
}

Haiku Operation System

V547 Expression is always true. Probably the '&&' operator should be used here. StatusView.cpp 1397


void
TDragRegion::Draw(BRect)
{
  ....
  if (fDragLocation != kDontDrawDragRegion ||
      fDragLocation != kNoDragRegion)
    DrawDragRegion();
}

Haiku Operation System

V547 Expression 'reservedBase < 0' is always false. Unsigned type value is never < 0. agp_gart.cpp 1172


/* address types */
typedef  unsigned long int  __haiku_addr_t;   // <=
typedef __haiku_addr_t    addr_t;             // <=

static status_t
bind_aperture(...., addr_t reservedBase, ....)
{
  ....
  if (status < B_OK) {
    if (reservedBase < 0)
      aperture->DeleteMemory(memory);

    return status;
  }
  ....
}

Haiku Operation System

V547 Expression 'nogscale >= 0' is always true. Unsigned type value is always >= 0. tvp3026.c 212


status_t mil2_dac_init (void)
{
  uint32   rfhcnt, nogscale, memconfig;
  ....
  for (nogscale = 1; nogscale >= 0; nogscale--) {           // <=
    int max = -1 + 33.2 * mclk / (nogscale? 1: 4);
    for (rfhcnt = 15; rfhcnt > 0; rfhcnt--) {
      int value = (rfhcnt & 0x0e) * 256 + (rfhcnt & 0x01) * 64;
      LOG(2,("mil2_dac_init factor %d, rfhcnt %2d: %d ?<= %d\n",
        nogscale, rfhcnt, value, max));
      if (value <= max) goto rfhcnt_found;
    }
  }
  ....
}

Godot Engine

V547 Expression 'p_bytes < 0' is always false. Unsigned type value is never < 0. memory_pool_static_malloc.cpp 159


void* MemoryPoolStaticMalloc::_realloc(void *p_memory,
                                       size_t p_bytes) {
  ....
  if (p_bytes<=0)
  {
    this->free(p_memory);
    ERR_FAIL_COND_V( p_bytes < 0 , NULL );
    return NULL;
  }
  ....
}

Godot Engine

V547 Expression 's < 0' is always false. Unsigned type value is never < 0. particles_2d.cpp 230


_FORCE_INLINE_ static float _rand_from_seed(uint32_t *seed)
{
  ....
  uint32_t s = (*seed);
  ....
  if (s < 0)
    s += 2147483647;
  ....
}

Unreal Engine 4

V547 Expression is always false. Unsigned type value is never < 0. windowsapplication.cpp 1938


void FWindowsApplication::QueryConnectedMice()
{
  ....
  if (GetRawInputDeviceInfoA(Device.hDevice, ....) < 0)
    continue;

  Name.Reset(new char[NameLen+1]);
  if (GetRawInputDeviceInfoA(Device.hDevice, ....) < 0)
    continue;
  ....
}

UINT WINAPI GetRawInputDeviceInfo(...);


MAME

V547 Expression 'nBit < 0' is always false. Unsigned type value is never < 0. bitmask.c 60


BOOL TestBit(LPBITS lpBits, UINT nBit)
{
  UINT  offset;
  UCHAR  mask;

  if (nBit < 0 || !lpBits || !lpBits->m_lpBits)
    return FALSE;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'nBit < 0' is always false. Unsigned type value is never < 0. bitmask.c 80
  • V547 Expression 'nBit < 0' is always false. Unsigned type value is never < 0. bitmask.c 100

Apple II emulator

V547 Expression 'uTStates < 0' is always false. Unsigned type value is never < 0. z80.cpp 5507


static const double uZ80ClockMultiplier = CLK_Z80 / CLK_6502;
inline static ULONG ConvertZ80TStatesTo6502Cycles(UINT uTStates)
{
  return (uTStates < 0) ?
    0 : (ULONG) ((double)uTStates / uZ80ClockMultiplier);
}

Gamer_Z eXtreme Party

V547 Expression is always true. Probably the '&&' operator should be used here. minigamederby.cxx 346


bool OnPlayerKeyStateChange(
  int playerid, int newkeys, int oldkeys) override
{
  if (newkeys == 1 || newkeys == 9 ||
      newkeys == 33 && oldkeys != 1 ||
      oldkeys != 9 || oldkeys != 33)       // <=
  {
    AddVehicleComponent(Player[playerid].CurrentVehicle, 1010);
  }
  return true;
}

Similar errors can be found in some other places:

  • V547 Expression is always true. Probably the '&&' operator should be used here. minigameracingsystem.cxx 528

Gamer_Z eXtreme Party

V547 Expression 'index >= 0' is always true. Unsigned type value is always >= 0. stunting.cxx 372


ZCMDF(tpx, PERMISSION_NONE,
      RESTRICTION_NOT_IN_A_GAME | RESTRICTION_NOT_AFTER_FIGHT,
      cmd_alias({}), "D")
{
  if (parser.Good())
  {
    size_t index = (_StuntPark.Objects.size() - 1) -
                   parser.Get<unsigned long>();
    if (index >= 0)
    {
      ....
    }
  }
  return true;
}

FreeSWITCH

V547 Expression is always false. Unsigned type value is never < 0. esl.c 690


typedef SOCKET ws_socket_t;

static ws_socket_t prepare_socket(ips_t *ips)
{
  ws_socket_t sock = ws_sock_invalid;

  ....
  if ((sock = socket(family, SOCK_STREAM, IPPROTO_TCP)) < 0) {
    die("Socket Error!\n");
  }
  ....
}

FreeSWITCH

V547 Expression 'fftstate->Perm == ((void *) 0)' is always false. Pointer 'fftstate->Perm' != NULL. fft.c 339


typedef struct {
  unsigned int SpaceAlloced;
  unsigned int MaxPermAlloced;
  double Tmp0[MAXFFTSIZE];
  double Tmp1[MAXFFTSIZE];
  double Tmp2[MAXFFTSIZE];
  double Tmp3[MAXFFTSIZE];
  int Perm[MAXFFTSIZE];
  int factor [NFACTOR];

} FFTstr;

static int   FFTRADIX (...., FFTstr *fftstate)
{
  ....
  if (fftstate->Tmp0 == NULL || fftstate->Tmp1 == NULL ||
      fftstate->Tmp2 == NULL || fftstate->Tmp3 == NULL ||
      fftstate->Perm == NULL) {
    return -1;
  }
  ....
}

Mozilla Thunderbird

V547 Expression is always false. Probably the '||' operator should be used here. nsmsgdbview.cpp 3014


class NS_NO_VTABLE nsMsgViewCommandType
{
  enum
  {
    ....
    junk = 27,
    unjunk = 28,
    ....
  };
};

nsresult nsMsgDBView::
ApplyCommandToIndices(nsMsgViewCommandTypeValue command, ....)
{
  ....
  if ((command == nsMsgViewCommandType::junk) &&
      (command == nsMsgViewCommandType::unjunk))
  ....
}

GINV

V547 Expression '* i ++ < 0' is always false. Unsigned type value is never < 0. imonomaux.cpp 460


class IMonomAuxInterface {
public:
  typedef unsigned         Word;
  typedef Word*            MonomIterator;
  typedef const Word*      MonomConstIterator;
  ....
}

bool IMonomAuxInterface::assertValid(
  IMonomAuxInterface::MonomConstIterator i) const
{
  MonomConstIterator end1 = i + mEndVar;
  do {
    if (*i++ < 0)
      return false;
  } while(i < end1);
  return true;
}

Unreal Engine 4

V547 Expression 'CurrentFileSize >= 0' is always true. Unsigned type value is always >= 0. buildpatchcompactifier.cpp 135


bool FBuildDataCompactifier::Compactify(....) const
{
  ....
  uint64 CurrentFileSize;
  ....
  CurrentFileSize = IFileManager::Get().FileSize(*File);
  if (CurrentFileSize >= 0)
  {
    ....
  }
  else
  {
    GLog->Logf(TEXT("Warning. ......"), *File);
  }
  ....
}

Dolphin Smalltalk 7

V547 Expression 'i >= 0' is always true. Unsigned type value is always >= 0. compact.cpp 35


// Answer the index of the last occuppied OT entry
unsigned __stdcall ObjectMemory::lastOTEntry()
{
  HARDASSERT(m_pOT);

  unsigned i = m_nOTSize-1;
  const OTE* pOT = m_pOT;
  while (pOT[i].isFree())
  {
    ASSERT(i >= 0);
    i--;
  }

  return i;
}

Similar errors can be found in some other places:

  • V547 Expression is always true. Unsigned type value is always >= 0. loadimage.cpp 343

Dolphin Smalltalk 7

V547 Expression 'ch > 127' is always false. The value range of char type: [-128, 127]. decode.cpp 55


ostream& operator<<(ostream& stream, ....)
{
  ....
  char ch = string->m_characters[i];
  //if (ch = '\0') break;
  if (ch < 32 || ch > 127)
  {
    static char hexChars[16+1] = "0123456789ABCDEF";
    ....
  }
  ....
}

ChakraCore

V547 Expression 'srcIndex - src->left >= 0' is always true. Unsigned type value is always >= 0. sparsearraysegment.inl 355


class SparseArraySegmentBase
{
public:
    static const uint32 MaxLength;
    ....
    uint32 size;
    ....
}

template<typename T>
SparseArraySegment<T>* SparseArraySegment<T>::CopySegment(....,
  uint32 srcIndex, ....)
{
  ....
  AssertMsg(srcIndex - src->left >= 0,                    // <=
    "src->left > srcIndex resulting in \
     negative indexing of src->elements");
  js_memcpy_s(dst->elements + dstIndex - dst->left,
              sizeof(T) * inputLen,
              src->elements + srcIndex - src->left,
              sizeof(T) * inputLen);
  return dst;
}

ChakraCore

V547 Expression is always true. Probably the '&&' operator should be used here. bytecodegenerator.cpp 805


void ByteCodeGenerator::AssignRegister(Symbol *sym)
{
  AssertMsg(sym->GetDecl() == nullptr ||
            sym->GetDecl()->nop != knopConstDecl ||      // <=
            sym->GetDecl()->nop != knopLetDecl, "....");

  if (sym->GetLocation() == Js::Constants::NoRegister)
  {
    sym->SetLocation(NextVarRegister());
  }
}

ChakraCore

V547 Expression 'callSiteId >= 0' is always true. Unsigned type value is always >= 0. inline.cpp 1181


typedef uint16 ProfileId;

Func * Inline::BuildInlinee(Js::FunctionBody* funcBody, ....)
{
  ....
  Js::ProfileId callSiteId = static_cast<Js::ProfileId>(....);
  Assert(callSiteId >= 0);
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'callSiteId >= 0' is always true. Unsigned type value is always >= 0. inline.cpp 2627
  • V547 Expression 'callSiteId >= 0' is always true. Unsigned type value is always >= 0. inline.cpp 3657

Computational Network Toolkit

V547 Expression 'val[0] == 0xEF' is always false. The value range of char type: [-128, 127]. file.cpp 462


bool File::IsUnicodeBOM(bool skip)
{
  ....
  else if (m_options & fileOptionsText)
  {
    char val[3];
    file.ReadString(val, 3);
    found = (val[0] == 0xEF && val[1] == 0xBB && val[2] == 0xBF);
  }
  // restore pointer if no BOM or we aren't skipping it
  if (!found || !skip)
  {
    SetPosition(pos);
  }
  ....
}

MPC-HC

V547 Expression '(SpeakerActivityMask & 0xC000) == 0x0C00' is always false. file_dts.cpp 196


std::string
DTS_HD_SpeakerActivityMask(int16u SpeakerActivityMask)
{
  ....
  if ((SpeakerActivityMask&0xC000)==0x0C00)
  ....
}

Note that 0xC000 and 0x0C00 are used. Apparently these values should have been the same.

Similar errors can be found in some other places:

  • V547 Expression '(SpeakerActivityMask & 0xC000) == 0x0C00' is always false. file_dts.cpp 264

FreeBSD Kernel

V547 Expression is always true. Probably the '&&' operator should be used here. qla_hw.c 799


static int
qla_tx_tso(qla_host_t *ha, struct mbuf *mp, ....)
{
  ....
  if ((*tcp_opt != 0x01) || (*(tcp_opt + 1) != 0x01) ||
    (*(tcp_opt + 2) != 0x08) || (*(tcp_opt + 2) != 10)) { // <=
    return -1;
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'value < 0' is always false. Unsigned type value is never < 0. ar9300_xmit.c 450

FreeBSD Kernel

V547 Expression 'cdb[0] != 0x28 || cdb[0] != 0x2A' is always true. Probably the '&&' operator should be used here. mfi_tbolt.c 1110


int
mfi_tbolt_send_frame(struct mfi_softc *sc, struct mfi_command*cm)
{
  ....
  if (cdb[0] != 0x28 || cdb[0] != 0x2A) {
    if ((req_desc = mfi_tbolt_build_mpt_cmd(sc, cm)) == NULL) {
      device_printf(sc->mfi_dev, "Mapping from MFI "
          "to MPT Failed \n");
      return 1;
    }
  }
  else
    device_printf(sc->mfi_dev, "DJA NA XXX SYSPDIO\n");
  ....
}

FreeBSD Kernel

V547 Expression is always true. Probably the '&&' operator should be used here. igmp.c 1939


static void
igmp_v3_suppress_group_record(struct in_multi *inm)
{
  ....
  if (inm->inm_state != IGMP_G_QUERY_PENDING_MEMBER ||
      inm->inm_state != IGMP_SG_QUERY_PENDING_MEMBER)
    return;
  ....
}

FreeBSD Kernel

V547 Expression 'j >= 0' is always true. Unsigned type value is always >= 0. safe.c 1596


static void
safe_mcopy(struct mbuf *srcm, struct mbuf *dstm, u_int offset)
{
  u_int j, dlen, slen;                   // <=
  caddr_t dptr, sptr;

  /*
   * Advance src and dst to offset.
   */
  j = offset;
  while (j >= 0) {                       // <=
    if (srcm->m_len > j)
      break;
    j -= srcm->m_len;                    // <=
    srcm = srcm->m_next;
    if (srcm == NULL)
      return;
  }
  sptr = mtod(srcm, caddr_t) + j;
  slen = srcm->m_len - j;

  j = offset;
  while (j >= 0) {                       // <=
    if (dstm->m_len > j)
      break;
    j -= dstm->m_len;                    // <=
    dstm = dstm->m_next;
    if (dstm == NULL)
      return;
  }
  dptr = mtod(dstm, caddr_t) + j;
  dlen = dstm->m_len - j;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'j >= 0' is always true. Unsigned type value is always >= 0. safe.c 1608

Oracle VM Virtual Box

V547 Expression is always false. Unsigned type value is never < 0. dt_subr.c 715


#define vsnprintf RTStrPrintfV

int
dt_printf(dtrace_hdl_t *dtp, FILE *fp, const char *format, ...)
{
  ....
  if (vsnprintf(
        &dtp->dt_buffered_buf[dtp->dt_buffered_offs],
        avail,
        format,
        ap) < 0) {                                   // <=
      rval = dt_set_errno(dtp, errno);
      va_end(ap);
      return (rval);
    }
  ....
}

size_t RTStrPrintfV(char *, size_t, const char *, va_list args); int vsnprintf (char *, size_t, const char *, va_list arg );


Oracle VM Virtual Box

V547 Expression 'sd >= 0' is always true. Unsigned type value is always >= 0. vboxservicevminfo.cpp 1086


static int vgsvcVMInfoWriteNetwork(void)
{
  ....
  SOCKET sd = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);
  ....
  if (pAdpInfo)
        RTMemFree(pAdpInfo);
  if (sd >= 0)
      closesocket(sd);
  ....
}

Serious Engine 1 v.1.10

V547 Expression is always false. Probably the '||' operator should be used here. entity.cpp 3537


enum RenderType {
  ....
  RT_BRUSH       = 4,
  RT_FIELDBRUSH  = 8,
  ....
};

void
CEntity::DumpSync_t(CTStream &strm, INDEX iExtensiveSyncCheck)
{
  ....
  if( en_pciCollisionInfo == NULL) {
    strm.FPrintF_t("Collision info NULL\n");
  } else if (en_RenderType==RT_BRUSH &&
             en_RenderType==RT_FIELDBRUSH) {
    strm.FPrintF_t("Collision info: Brush entity\n");
  } else {
  ....
  }
  ....
}

Serious Engine 1 v.1.10

V547 Expression is always true. Probably the '&&' operator should be used here. propertycombobar.cpp 1853


CEntity *CPropertyComboBar::GetSelectedEntityPtr(void)
{
 // obtain selected property ID ptr
 CPropertyID *ppidProperty = GetSelectedProperty();
 // if there is valid property selected
 if( (ppidProperty == NULL) ||
 (ppidProperty->pid_eptType != CEntityProperty::EPT_ENTITYPTR) ||
 (ppidProperty->pid_eptType != CEntityProperty::EPT_PARENT) )
 {
   return NULL;
 }
 ....
}

Serious Engine 1 v.1.10

V547 Expression 'ulUsedShadowMemory >= 0' is always true. Unsigned type value is always >= 0. gfxlibrary.cpp 1693


void CGfxLibrary::ReduceShadows(void)
{
  ULONG ulUsedShadowMemory = ....;
  ....
  ulUsedShadowMemory -= sm.Uncache();
  ASSERT( ulUsedShadowMemory>=0);
  ....
}

Serious Engine 1 v.1.10

V547 Expression 'achrLine != ""' is always true. To compare strings you should use strcmp() function. worldeditor.cpp 2254


void CWorldEditorApp::OnConvertWorlds()
{
  ....
  char achrLine[256];
  CTFileStream fsFileList;

  // count lines in list file
  try {
    fsFileList.Open_t( fnFileList);
    while( !fsFileList.AtEOF()) {
      fsFileList.GetLine_t( achrLine, 256);
      // increase counter only for lines that are not blank
      if( achrLine != "") ctLines++; // <=
    }
    fsFileList.Close();
  }
  ....
}

if(strcmp(achrLine, "") != 0) ctLines++;

Similar errors can be found in some other places:

  • V547 Expression is always true. To compare strings you should use strcmp() function. propertycombobar.cpp 965
  • V547 Expression 'achrLine == ""' is always false. To compare strings you should use strcmp() function. worldeditor.cpp 2293

OpenToonz

V547 Expression '(int) startOutPoints.size() % 2 != 2' is always true. rasterselection.cpp 852


TStroke getIntersectedStroke(TStroke &stroke, TRectD bbox)
{
  ....
  for (t = 0; t < (int)outPoints.size(); t++)
    addPointToVector(...., (int)startOutPoints.size() % 2 != 2);
  ....
}

PHP:Hypertext Preprocessor

V547 Expression is always false. Unsigned type value is never < 0. spl_directory.c 2886


#define MIN(a, b)   (((a)<(b))?(a):(b))
#define MAX(a, b)  (((a)>(b))?(a):(b))

SPL_METHOD(SplFileObject, fwrite)
{
  ....
  size_t str_len;
  zend_long length = 0;
  ....
  str_len = MAX(0, MIN((size_t)length, str_len));
  ....
}

Firebird

V547 Expression 'bdb->bdb_page.getPageNum() >= 0' is always true. Unsigned type value is always >= 0. cch.cpp 4827


static bool write_page(thread_db* tdbb, BufferDesc* bdb, ....)
{
  ....
  if (bdb->bdb_page.getPageNum() >= 0)
  ....
}

7-Zip

V547 Expression 'newSize < 0' is always false. Unsigned type value is never < 0. update.cpp 254


STDMETHODIMP COutMultiVolStream::SetSize(UInt64 newSize)
{
  if (newSize < 0)
    return E_INVALIDARG;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'rec.SiAttr.SecurityId >= 0' is always true. Unsigned type value is always >= 0. ntfshandler.cpp 2142
  • V547 Expression 's.Len() >= 0' is always true. Unsigned type value is always >= 0. xarhandler.cpp 258

Open X-Ray Engine

V547 Expression is always true. Probably the '&&' operator should be used here. configs_dumper.cpp 262


void configs_dumper::dumper_thread(void* my_ptr)
{
  ....
  DWORD wait_result = WaitForSingleObject(
             this_ptr->m_make_start_event, INFINITE);
  while ( wait_result != WAIT_ABANDONED) ||
         (wait_result != WAIT_FAILED))
  ....
}

Open X-Ray Engine

V547 Expression 'squad->get_index(this) == u32(- 1)' is always false. The value range of unsigned char type: [0, 255]. ai_rat.cpp 480


void CAI_Rat::UpdateCL()
{
  ....
  if (!Useful()) {
    inherited::UpdateCL        ();
    Exec_Look                  (Device.fTimeDelta);

    CMonsterSquad *squad = monster_squad().get_squad(this);

    if (squad && ((squad->GetLeader() != this &&
                  !squad->GetLeader()->g_Alive()) ||
                 squad->get_index(this) == u32(-1)))
      squad->SetLeader(this);

    ....
  }
  ....
}

Open X-Ray Engine

V547 Expression 'm_tActionCondition.m_tLifeTime >= 0' is always true. Unsigned type value is always >= 0. script_entity_action_inline.h 115


namespace ALife
{
  typedef u64 _TIME_ID;
}
ALife::_TIME_ID CScriptActionCondition::m_tLifeTime;

IC bool CScriptEntityAction::CheckIfTimeOver()
{
  return((m_tActionCondition.m_tLifeTime >= 0) &&
         ((m_tActionCondition.m_tStartTime +
           m_tActionCondition.m_tLifeTime)
                        < Device.dwTimeGlobal));
}

Similar errors can be found in some other places:

  • V547 Expression 'm_tActionCondition.m_tLifeTime < 0' is always false. Unsigned type value is never < 0. script_entity_action_inline.h 143

CPython

V547 Expression 's->sock_fd < 0' is always false. Unsigned type value is never < 0. socketmodule.c 655


#ifdef MS_WINDOWS
typedef SOCKET SOCKET_T;
#else
typedef int SOCKET_T;
#endif
typedef struct {
  PyObject_HEAD
  SOCKET_T sock_fd; /* Socket file descriptor */
  ....
} PySocketSockObject;

static int
internal_select(PySocketSockObject *s,
                int writing,
                _PyTime_t interval,
                int connect)
{
  ....
  if (s->sock_fd < 0)
    return 0;
  ....
}

CryEngine V

V547 Expression 'pszScript[iSrcBufPos] != '=='' is always true. The value range of char type: [-128, 127]. luadbg.cpp 716


bool CLUADbg::LoadFile(const char* pszFile, bool bForceReload)
{
  FILE* hFile = NULL;
  char* pszScript = NULL, * pszFormattedScript = NULL;
  ....
  while (pszScript[iSrcBufPos] != ' ' &&
    ....
    pszScript[iSrcBufPos] != '=' &&
    pszScript[iSrcBufPos] != '==' &&
    pszScript[iSrcBufPos] != '*' &&
    pszScript[iSrcBufPos] != '+' &&
    pszScript[iSrcBufPos] != '/' &&
    pszScript[iSrcBufPos] != '~' &&
    pszScript[iSrcBufPos] != '"')
  {}
  ....
}

CryEngine V

V547 Expression 'm_socket < 0' is always false. Unsigned type value is never < 0. servicenetwork.cpp 585


typedef SOCKET CRYSOCKET;
// Internal socket data
CRYSOCKET m_socket;

bool CServiceNetworkConnection::TryReconnect()
{
  ....
  // Create new socket if needed
  if (m_socket == 0)
  {
    m_socket = CrySock::socketinet();
    if (m_socket < 0)
    {
      ....
      return false;
    }
  }
  ....
}

ICQ

V547 Expression '"audio_playback_mute"' is always true. core im_container.cpp 329


void core::im_container::on_voip_call_message(....)
{
  ....
  } else if (type == "update") {
  ....
  } else if (type == "voip_set_window_offsets") {
  ....
  } else if (type == "voip_reset") {
  ....
  else if ("audio_playback_mute")
  {
    const std::string mode = _params.get_value_as_string("mute");
    im->on_voip_set_mute(mode == "on");
  }
  else {
    assert(false);
  }
}

CodeLite

V547 Expression 'type.Lower() == "Array"' is always false. NodeJSOuptutParser.h 61


struct NodeJSHandle {
  wxString type;
  ....
  bool IsString() const {return type.Lower() == "string";}
  bool IsArray() const {return type.Lower() == "Array"; }
};

LLVM/Clang

V547 Expression is always true. Probably the '&&' operator should be used here. LoopInterchange.cpp 208


static bool containsNoDependence(CharMatrix &DepMatrix,
                                 unsigned Row,
                                 unsigned Column) {
  for (unsigned i = 0; i < Column; ++i) {
    if (DepMatrix[Row][i] != '=' || DepMatrix[Row][i] != 'S' ||
        DepMatrix[Row][i] != 'I')
      return false;
  }
  return true;
}

Partio

V547 Expression '"R"' is always true. PDA.cpp 90


ParticlesDataMutable* readPDA(....)
{
  ....
  if(word == "V"){
      attrs.push_back(simple->addAttribute(....);
  }else if("R"){                                  // <=
      attrs.push_back(simple->addAttribute(....);
  }else if("I"){                                  // <=
      attrs.push_back(simple->addAttribute(....);
  }
  ....
}

OpenSubdiv

V547 Expression 'buffer[0] == '\r' && buffer[0] == '\n ' ' is always false. Probably the '||' operator should be used here. hdr_reader.cpp 84


unsigned char *loadHdr(....)
{
  ....
  if (! fgets(buffer, MAXLINE, fp)) goto error;
  if (buffer[0] == '\n') break;
  if (buffer[0] == '\r' && buffer[0] == '\n') break;
  ....
}

Linux Kernel

V547 Expression '(ptr[3] & 0x1E) != 0x03' is always true. sd.c 4115


int ext_sd_send_cmd_get_rsp(struct rtsx_chip *chip,
    u8 cmd_idx, u32 arg, u8 rsp_type,
    u8 *rsp, int rsp_len, bool special_check)
{
  int retval;
  int timeout = 100;
  u16 reg_addr;
  u8 *ptr;

  ....

  if (cmd_idx == SELECT_CARD) {
    if (rsp_type == SD_RSP_TYPE_R2) {
      if ((ptr[3] & 0x1E) != 0x04) {
        rtsx_trace(chip);
        return STATUS_FAIL;
      }

    } else if (rsp_type == SD_RSP_TYPE_R0) {
      if ((ptr[3] & 0x1E) != 0x03) {           // <=
        rtsx_trace(chip);
        return STATUS_FAIL;
      }
    }
  }

  ....
}

Linux Kernel

V547 Expression 'block' is always true. svclock.c 873


void
nlmsvc_grant_reply(struct nlm_cookie *cookie, __be32 status)
{
  struct nlm_block  *block;

  dprintk("grant_reply: looking for cookie %x, s=%d \n",
    *(unsigned int *)(cookie->data), status);
  if (!(block = nlmsvc_find_block(cookie)))
    return;

  if (block) {
    if (status == nlm_lck_denied_grace_period) {
      /* Try again in a couple of seconds */
      nlmsvc_insert_block(block, 10 * HZ);
    } else {
      /* Lock is now held by client, or has been rejected.
       * In both cases, the block should be removed. */
      nlmsvc_unlink_block(block);
    }
  }
  nlmsvc_release_block(block);
}

Linux Kernel

V547 Expression 'sym' is always true. menu.c 498


bool menu_is_visible(struct menu *menu)
{
  struct menu *child;
  struct symbol *sym;

  ....

  if (!sym || sym_get_tristate_value(menu->sym) == no) // <=
    return false;

  for (child = menu->list; child; child = child->next) {
    if (menu_is_visible(child)) {
      if (sym)                                         // <=
        sym->flags |= SYMBOL_DEF_USER;
      return true;
    }
  }

  return false;
}

CMaNGOS

V547 Expression is always false. Probably the '||' operator should be used here. SpellEffects.cpp 2872


void Spell::EffectEnchantItemTmp(SpellEffectIndex eff_idx)
{
  ....
  // TODO: Strange stuff in following code
  // shaman family enchantments
  if (....)
      duration = 300;
  else if (m_spellInfo->SpellIconID == 241 &&
           m_spellInfo->Id != 7434)
      duration = 3600;
  else if (m_spellInfo->Id == 28891 &&               // <=
           m_spellInfo->Id == 28898)
      duration = 3600;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression is always true. Probably the '&&' operator should be used here. genrevision.cpp 261
  • V547 Expression is always true. Probably the '&&' operator should be used here. vmapexport.cpp 361
  • V547 Expression is always true. Probably the '&&' operator should be used here. MapTree.cpp 125
  • And 1 additional diagnostic messages.

FreeBSD Kernel

V547 Expression 'cfgflags >= 0 || cfgflags <= 3' is always true. hwpmc_piv.c 812


static int
p4_config_pmc(int cpu, int ri, struct pmc *pm)
{
  ....
  int cfgflags, cpuflag;
  ....
  KASSERT(cfgflags >= 0 || cfgflags <= 3,
      ("[p4,%d] illegal cfgflags cfg=%d on cpu=%d ri=%d",
    __LINE__, cfgflags, cpu, ri));
  ....
  KASSERT(cfgflags >= 0 || cfgflags <= 3,
      ("[p4,%d] illegal runcount cfg=%d on cpu=%d ri=%d",
    __LINE__, cfgflags, cpu, ri));
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'cfgflags >= 0 || cfgflags <= 3' is always true. hwpmc_piv.c 838
  • V547 Expression 'cdb[0] != 0x28 || cdb[0] != 0x2A' is always true. Probably the '&&' operator should be used here. mfi_tbolt.c 1110

RPCS3

V547 Expression 'sock < 0' is always false. Unsigned type value is never < 0. sys_net.cpp 695


#ifdef _WIN32
  using socket_t = SOCKET;
#else
  using socket_t = int;
#endif

s32 socket(s32 family, s32 type, s32 protocol)
{
  ....
  socket_t sock = ::socket(family, type, protocol);

  if (sock < 0)
  {
    libnet.error("socket()....", get_errno() = get_last_error());
    return -1;
  }
  ....
}

FreeBSD Kernel

V547 Expression is always false. Unsigned type value is never < 0. ng_nat.c 374


unsigned int
LibAliasSetMode(struct libalias *, unsigned int _flags,
                unsigned int _mask);

static int
ng_nat_rcvmsg(node_p node, item_p item, hook_p lasthook)
{
  ....
  if (LibAliasSetMode(priv->lib,
      ng_nat_translate_flags(mode->flags),
      ng_nat_translate_flags(mode->mask)) < 0) {
    error = ENOMEM;
    break;
  }
  ....
}

FreeBSD Kernel

V547 Expression is always false. scif_sas_controller.c 531


....
U16  max_ncq_depth;
....
SCI_STATUS scif_user_parameters_set(
   SCI_CONTROLLER_HANDLE_T   controller,
   SCIF_USER_PARAMETERS_T  * scif_parms
)
{
  ....
   if (scif_parms->sas.max_ncq_depth < 1 &&
       scif_parms->sas.max_ncq_depth > 32)
     return SCI_FAILURE_INVALID_PARAMETER_VALUE;
  ....
}

CryEngine V

V547 Expression 'outArrIndices[i] < 0' is always false. Unsigned type value is never < 0. CGFLoader.cpp 881


static bool CompactBoneVertices(....,
  DynArray<uint16>& outArrIndices, ....)           // <= uint16
{
  ....
  outArrIndices.resize(3 * inFaceCount, -1);

  int outVertexCount = 0;
  for (int i = 0; i < verts.size(); ++i)
  {
    ....
    outArrIndices[....] = outVertexCount - 1;
  }

  // Making sure that the code above has no bugs   // <= LOL
  for (int i = 0; i < outArrIndices.size(); ++i)
  {
    if (outArrIndices[i] < 0)                      // <= LOL
    {
      return false;
    }
  }

  return true;
}

TensorFlow

V547 Expression 'to_unref' is always false. master_session.cc 1114


Status MasterSession::StartStep(const BuildGraphOptions& opts,
                                int64* count,
                                ReffedClientGraph** rcg,
                                bool is_partial) {
  ....
  ReffedClientGraph* to_unref = nullptr;
  ....
  if (to_unref) to_unref->Unref();
  ....
}

Valgrind

V547 Expression 'ce->off >= 0' is always true. Unsigned type value is always >= 0. image.c 147


typedef  ULong  DiOffT;

typedef
   struct {
      Bool   fromC;
      DiOffT off;
      SizeT  size;
      SizeT  used;
      UChar  data[];
   }
   CEnt;

static Bool is_sane_CEnt ( .... )
{
  ....
  CEnt* ce = img->ces[i];
  ....
  if (!(ce->size == CACHE_ENTRY_SIZE)) goto fail;
  if (!(ce->off >= 0)) goto fail;
  if (!(ce->off + ce->used <= img->real_size)) goto fail;
  ....
}

Valgrind

V547 Expression '((void *) 0)' is always false. server.c 110


#define NULL ((void *) 0)

void reset_valgrind_sink(const char *info)
{
   if (VG_(log_output_sink).fd != initial_valgrind_sink.fd
       && initial_valgrind_sink_saved) {
      VG_(log_output_sink).fd = initial_valgrind_sink.fd;
      VG_(umsg) ("Reset valgrind output to log (%s)\n",
                 (info = NULL ? "" : info));                // <=
   }
}

Most likely this is what should be written here: (info == NULL ? "" : info)


ALSA

V547 Expression is always false. pcm_extplug.c 769


int snd_pcm_extplug_set_slave_param_list(
  snd_pcm_extplug_t *extplug, int type, unsigned int num_list,
  const unsigned int *list)
{
  extplug_priv_t *ext = extplug->pcm->private_data;
  if (type < 0 && type >= SND_PCM_EXTPLUG_HW_PARAMS) {     // <=
    SNDERR("EXTPLUG: invalid parameter type %d", type);
    return -EINVAL;
  }
  return snd_ext_parm_set_list(&ext->sparams[type],
                               num_list, list);
}

Most likely this is what should be written here: (type < 0 || type >= SND_PCM_EXTPLUG_HW_PARAMS)

Similar errors can be found in some other places:

  • V547 Expression is always false. pcm_extplug.c 791
  • V547 Expression is always false. pcm_extplug.c 817
  • V547 Expression is always false. pcm_extplug.c 839
  • And 2 additional diagnostic messages.

Aspell

V547 Expression 'pathPosEnd >= 0' is always true. Unsigned type value is always >= 0. new_fmode.cpp 566


class String : public OStream
{
  ....
  static const size_t npos = INT_MAX;

  size_t find(char c, size_t pos = 0) const {
    char * res = (char *)memchr(begin_ + pos, c, size() - pos);
    if (res == 0) return npos;
    else return res - begin_;
  }
  ....
};

PosibErr<FilterModeList *> FilterModeList::get_new(
  const String & key, const Config *)
{
  ....
  String possMode;
  ....
  unsigned pathPos = 0;
  unsigned pathPosEnd = 0;
  ....
  while (    ( (pathPosEnd =
                  possMode.find('/',pathPos)) < possMode.size() )
          && ( pathPosEnd >= 0 ) ) {
    pathPos = pathPosEnd + 1;
  }
  ....
}

SCIM

V547 Expression 'epos >= 0' is always true. Unsigned type value is always >= 0. scim_anthy_style_file.cpp 103


StyleLineType StyleLine::get_type (void)
{
  ....
  unsigned int spos, epos;
  ....
  for (epos = m_line.length () - 1;
       epos >= 0 && isspace (m_line[epos]);
       epos--);
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'epos >= 0' is always true. Unsigned type value is always >= 0. scim_anthy_style_file.cpp 137

Tizen

V547 Expression is always true. Probably the '&&' operator should be used here. bluetooth-hid.c 229


typedef enum {
  BT_HID_MOUSE_BUTTON_NONE = 0x00,
  BT_HID_MOUSE_BUTTON_LEFT = 0x01,
  BT_HID_MOUSE_BUTTON_RIGHT = 0x02,
  BT_HID_MOUSE_BUTTON_MIDDLE = 0x04
} bt_hid_mouse_button_e;

int bt_hid_device_send_mouse_event(const char *remote_address,
  const bt_hid_mouse_data_s *mouse_data)
{
  ....
  if (mouse_data->buttons != BT_HID_MOUSE_BUTTON_LEFT ||
      mouse_data->buttons != BT_HID_MOUSE_BUTTON_RIGHT ||
      mouse_data->buttons != BT_HID_MOUSE_BUTTON_MIDDLE) {
    return BT_ERROR_INVALID_PARAMETER;
  }
  ....
}

Tizen

V547 Expression 'm_candiPageFirst < 0' is always false. Unsigned type value is never < 0. imi_view_classic.cpp 201


unsigned m_candiPageFirst;

bool
CIMIClassicView::onKeyEvent(const CKeyEvent& key)
{
  ....
  if (m_candiPageFirst > 0) {
    m_candiPageFirst -= m_candiWindowSize;
    if (m_candiPageFirst < 0) m_candiPageFirst = 0;
    changeMasks |= CANDIDATE_MASK;
  }
  ....
}

Tizen

V547 Expression 'itemData' is always true. QuickAccess.cpp 571


void
QuickAccess::_grid_mostVisited_del(void *data, Evas_Object *)
{
  BROWSER_LOGD("[%s:%d]", __PRETTY_FUNCTION__, __LINE__);
  if (data) {
    auto itemData = static_cast<HistoryItemData*>(data);
    if (itemData)
      delete itemData;
  }
}

Similar errors can be found in some other places:

  • V547 Expression '!urlPair' is always false. GenlistManager.cpp 143
  • V547 Expression 'item_name' is always true. SettingsUI.cpp 222
  • V547 Expression 'item_name' is always true. SettingsUI.cpp 226
  • And 1 additional diagnostic messages.

Tizen

V547 Expression 'strlen(s_formatted) < 128' is always true. clock.c 503


#define CLOCK_STR_LEN 128

void indicator_get_time_by_region(char* output,void *data)
{
  ....
  char s_formatted[CLOCK_STR_LEN] = { 0, };
  ....
  if (strlen(s_formatted) < CLOCK_STR_LEN) {            // <=
    strncpy(output, s_formatted, strlen(s_formatted));
  }
  else {
    strncpy(output, s_formatted, CLOCK_STR_LEN - 1);
  }

  return;
}

Tizen

V547 Expression 'doc != NULL' is always true. setting-common-data-slp-setting.c 1450


static void _parseLangListXML(char *docname)
{
  SETTING_TRACE_BEGIN;
  xmlDocPtr doc;
  xmlNodePtr cur;

  doc = xmlParseFile(docname);

  if (doc == NULL) {
    fprintf(stderr, "Document not parsed successfully. \n");
    return;
  }
  ....
  if (doc != NULL) {
    xmlFreeDoc(doc);
  }
  return;
}

EFL Core Libraries

V547 Expression '(status < 500) && (status > 599)' is always false. ecore_con_url.c 351


static void
_ecore_con_url_dialer_error(void *data, const Efl_Event *event)
{
   Ecore_Con_Url *url_con = data;
   Eina_Error *perr = event->info;
   int status;

   status =
     efl_net_dialer_http_response_status_get(url_con->dialer);

   if ((status < 500) && (status > 599))
   {
      DBG("HTTP error %d reset to 1", status);
      status = 1; /* not a real HTTP error */
   }

   WRN("HTTP dialer error url='%s': %s",
       efl_net_dialer_address_dial_get(url_con->dialer),
       eina_error_msg_get(*perr));

   _ecore_con_event_url_complete_add(url_con, status);
}

Similar errors can be found in some other places:

  • V547 Expression '(status < 500) && (status > 599)' is always false. ecore_con_url.c 658
  • V547 Expression '(status < 500) && (status > 599)' is always false. ecore_con_url.c 1340

EFL Core Libraries

V547 Expression 'match' is always true. eina_rectangle.c 798


EAPI void
eina_rectangle_pool_release(Eina_Rectangle *rect)
{
  Eina_Rectangle *match;
  Eina_Rectangle_Alloc *new;
  ....
  match =(Eina_Rectangle *) (new + 1);
  if (match)
    era->pool->empty = _eina_rectangle_skyline_list_update(
                          era->pool->empty, match);
  ....
}

EFL Core Libraries

V547 Expression 's' is always true. evas_object_smart.c 160


EAPI const void *
evas_object_smart_interface_get(const Evas_Object *eo_obj,
                                const char *name)
{
  Evas_Smart *s;
  ....
  s = evas_object_smart_smart_get(eo_obj);
  if (!s) return NULL;

  if (s)
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 's' is always true. evas_object_smart.c 192
  • V547 Expression '!c->fmt' is always true. evas_object_textblock.c 6359
  • V547 Expression '!cur->node' is always true. evas_object_textblock.c 9943
  • And 30 additional diagnostic messages.

ClickHouse

V547 Expression 'val > 0xffffu' is always false. The value range of unsigned short type: [0, 65535]. FunctionsCoding.h 339


static void ipv6_scan(const char *  src, unsigned char * dst)
{
  ....
  uint16_t val{};
  unsigned char * colonp = nullptr;

  while (const auto ch = *src++)
  {
    const auto num = unhex(ch);

    if (num != -1)
    {
      val <<= 4;
      val |= num;
      if (val > 0xffffu)         // <=
        return clear_dst();
  ....
}

ClickHouse

V547 Expression 'offset > 0' is always true. FunctionsCoding.h 649


static void formatIP(UInt32 ip, char *& out)
{
  ....
  for (size_t offset = 8; offset <= 24; offset += 8)
  {
    if (offset > 0)
      *(out++) = '.';
  ....
}

MuseScore

V547 Expression 'middleMeasure != 0' is always false. ove.cpp 7852


bool
getMiddleUnit(...., Measure* middleMeasure, int& middleUnit) {
  ....
}

void OveOrganizer::organizeWedge(....) {
  ....
  Measure* middleMeasure = NULL;
  int middleUnit = 0;

  getMiddleUnit(
    ove_, part, track,
    measure, ove_->getMeasure(bar2Index),
    wedge->start()->getOffset(), wedge->stop()->getOffset(),
    middleMeasure, middleUnit);

  if( middleMeasure != 0 ) {                            // <=
    WedgeEndPoint* midStopPoint = new WedgeEndPoint();
    measureData->addMusicData(midStopPoint);

    midStopPoint->setTick(wedge->getTick());
    midStopPoint->start()->setOffset(middleUnit);
    midStopPoint->setWedgeStart(false);
    midStopPoint->setWedgeType(WedgeType::Cres_Line);
    midStopPoint->setHeight(wedge->getHeight());

    WedgeEndPoint* midStartPoint = new WedgeEndPoint();
    measureData->addMusicData(midStartPoint);

    midStartPoint->setTick(wedge->getTick());
    midStartPoint->start()->setOffset(middleUnit);
    midStartPoint->setWedgeStart(true);
    midStartPoint->setWedgeType(WedgeType::Decresc_Line);
    midStartPoint->setHeight(wedge->getHeight());
    }
  }
  ....
}

Typo: middleMeasure and middleUnit.


MuseScore

V547 Expression 'error == 2' is always false. mididriver.cpp 126


#define ENOENT 2

bool AlsaMidiDriver::init()
{
  int error = snd_seq_open(&alsaSeq, "hw", ....);
  if (error < 0) {
    if (error == ENOENT)
      qDebug("open ALSA sequencer failed: %s",
        snd_strerror(error));
    return false;
  }
  ....
}

Rosegarden

V547 Expression '!beamedSomething' is always true. SegmentNotationHelper.cpp 1405


void SegmentNotationHelper::makeBeamedGroupAux(....)
{
  int groupId = segment().getNextId();
  bool beamedSomething = false;

  for (iterator i = from; i != to; ++i) {
  ....
  if ((*i)->isa(Note::EventType) &&
    (*i)->getNotationDuration() >= Note(....).getDuration()) {
    if (!beamedSomething) continue;         // <=
    iterator j = i;
    bool somethingLeft = false;
    while (++j != to) {
      if ((*j)->getType() == Note::EventType &&
        (*j)->getNotationAbsoluteTime() > (*i)->get....() &&
        (*j)->getNotationDuration() < Note(....).getDuration()) {
        somethingLeft = true;
        break;
      }
    }
    if (!somethingLeft) continue;
  }
  ....
}

Rosegarden

V547 Expression 'i > 5' is always false. SegmentParameterBox.cpp 323


void SegmentParameterBox::initBox()
{
  ....
  for (int i = 0; i < 6; i++) {
    timeT time = 0;
    if (i > 0 && i < 6) {
        time = Note(Note::Hemidemisemiquaver).get.... << (i - 1);
    } else if (i > 5) {
        time = Note(Note::Crotchet).getDuration() * (i - 4);
    }
  ....
}

Rosegarden

V547 Expression 'adjustedOctave < 8' is always false. NotePixmapFactory.cpp 1920


QGraphicsPixmapItem* NotePixmapFactory::makeClef(....)
{
  ....
  int oct = clef.getOctaveOffset();
  if (oct == 0) return plain.makeItem();

  int adjustedOctave = (8 * (oct < 0 ? -oct : oct));
  if (adjustedOctave > 8)
      adjustedOctave--;
  else if (adjustedOctave < 8)
      adjustedOctave++;
  ....
}

Rosegarden

V547 Expression '""' is always true. LilyPondOptionsDialog.cpp 64


LilyPondOptionsDialog::LilyPondOptionsDialog(....)
{
  setModal(true);
  setWindowTitle((windowCaption = "" ?
    tr("LilyPond Export/Preview") : windowCaption));
  ....
}

Similar errors can be found in some other places:

  • V547 Expression '""' is always true. MusicXMLOptionsDialog.cpp 60

Ardour

V547 Expression 'strlen(buf) < 256' is always true. vst_info_file.cc 262


static char *
read_string (FILE *fp)
{
  char buf[MAX_STRING_LEN];

  if (!fgets (buf, MAX_STRING_LEN, fp)) {
    return 0;
  }

  if (strlen (buf) < MAX_STRING_LEN) {
    if (strlen (buf)) {
      buf[strlen (buf)-1] = 0;
    }
    return strdup (buf);
  } else {
    return 0;
  }
}

Sphinx (search engine)

V547 Expression is always false. sphinx.cpp 22416


enum ESphBinRead
{
  BIN_READ_OK,        ///< bin read ok
  BIN_READ_EOF,       ///< bin end
  BIN_READ_ERROR,     ///< bin read error
  BIN_PRECACHE_OK,    ///< precache ok
  BIN_PRECACHE_ERROR  ///< precache failed
};

ESphBinRead CSphBin::ReadBytes ( void * pDest, int iBytes )
{
  ....
    return BIN_READ_EOF;
  ....
    return BIN_READ_ERROR;
  ....
  return BIN_READ_OK;
}

static void DictReadEntry (....)
{
  ....
  if ( pBin->ReadBytes ( pKeyword, iKeywordLen )<0 )    // <=
  {
    assert ( pBin->IsError() );
    return;
  }
  ....
}

V8 JavaScript Engine

V547 CWE-570 Expression 'truncated' is always false. objects.cc 2867


void String::StringShortPrint(StringStream* accumulator,
                              bool show_details) {
  int len = length();
  if (len > kMaxShortPrintLength) {
    accumulator->Add("<Very long string[%u]>", len);
    return;
  }

  if (!LooksValid()) {
    accumulator->Add("<Invalid String>");
    return;
  }

  StringCharacterStream stream(this);

  bool truncated = false;
  if (len > kMaxShortPrintLength) {
    len = kMaxShortPrintLength;
    truncated = true;
  }
  bool one_byte = true;
  for (int i = 0; i < len; i++) {
    uint16_t c = stream.GetNext();

    if (c < 32 || c >= 127) {
      one_byte = false;
    }
  }
  stream.Reset(this);
  if (one_byte) {
    if (show_details)
      accumulator->Add("<String[%u]: ", length());
    for (int i = 0; i < len; i++) {
      accumulator->Put(static_cast<char>(stream.GetNext()));
    }
    if (show_details) accumulator->Put('>');
  } else {
    // Backslash indicates that the string contains control
    // characters and that backslashes are therefore escaped.
    if (show_details)
      accumulator->Add("<String[%u]\\: ", length());
    for (int i = 0; i < len; i++) {
      uint16_t c = stream.GetNext();
      if (c == '\n') {
        accumulator->Add("\\n");
      } else if (c == '\r') {
        accumulator->Add("\\r");
      } else if (c == '\\') {
        accumulator->Add("\\\\");
      } else if (c < 32 || c > 126) {
        accumulator->Add("\\x%02x", c);
      } else {
        accumulator->Put(static_cast<char>(c));
      }
    }
    if (truncated) {                      // <=
      accumulator->Put('.');
      accumulator->Put('.');
      accumulator->Put('.');
    }
    if (show_details) accumulator->Put('>');
  }
  return;
}

V8 JavaScript Engine

V547 CWE-570 Expression 'inf == - 1' is always false. string-stream.cc 149


void StringStream::Add(....) {
  ....
    case 'f': case 'g': case 'G': case 'e': case 'E': {
      double value = current.data_.u_double_;
      int inf = std::isinf(value);
      if (inf == -1) {
        Add("-inf");
      } else if (inf == 1) {
        Add("inf");
      } else if (std::isnan(value)) {
        Add("nan");
      } else {
        EmbeddedVector<char, 28> formatted;
        SNPrintF(formatted, temp.start(), value);
        Add(formatted.start());
      }
      break;
    }  ....
}

Description of the std::isinf function: http://en.cppreference.com/w/cpp/numeric/math/isinf As you can see, the function std::isinf returns the bool type. Thus, the function is clearly used incorrectly.


Protocol Buffers

V547 CWE-571 Expression is always true. time.cc 83


static const int kDaysInMonth[13] = {
  0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};

bool ValidateDateTime(const DateTime& time) {
  if (time.year < 1 || time.year > 9999 ||
      time.month < 1 || time.month > 12 ||
      time.day < 1 || time.day > 31 ||
      time.hour < 0 || time.hour > 23 ||
      time.minute < 0 || time.minute > 59 ||
      time.second < 0 || time.second > 59) {
    return false;
  }
  if (time.month == 2 && IsLeapYear(time.year)) {
    return time.month <= kDaysInMonth[time.month] + 1;
  } else {
    return time.month <= kDaysInMonth[time.month];
  }
}

Details: https://www.viva64.com/en/b/0550/

Similar errors can be found in some other places:

  • V547 CWE-571 Expression 'time.month <= kDaysInMonth[time.month]' is always true. time.cc 85

RE2

V547 CWE-570 Expression 'c1 == c' is always false. rune.cc 247


typedef signed int Rune;

enum
{
  UTFmax    = 4,
  Runesync  = 0x80,
  Runeself  = 0x80,
  Runeerror = 0xFFFD,
  Runemax   = 0x10FFFF,
};

char*
utfrune(const char *s, Rune c)
{
  long c1;
  Rune r;
  int n;

  if(c < Runesync)    /* not part of utf sequence */
    return strchr((char*)s, c);

  for(;;) {
    c1 = *(unsigned char*)s;
    if(c1 < Runeself) {  /* one byte rune */
      if(c1 == 0)
        return 0;
      if(c1 == c)                // <=
        return (char*)s;
      s++;
      continue;
    }
    n = chartorune(&r, s);
    if(r == c)
      return (char*)s;
    s += n;
  }
  return 0;
}

If the variable c < 0x80, the function ends its work. This means that the value of a variable (c)>= 0x80. A comparison, interesting for us is performed only in case if c1 < 0x80. If c >= 80 and c1 < 0x80, the c==c1 a condition will always be false.


Skia Graphics Engine

V547 CWE-571 Expression 'allDone' is always true. skopcontour.cpp 43


SkOpSpan* SkOpContour::undoneSpan() {
  SkOpSegment* testSegment = &fHead;
  bool allDone = true;
  do {
    if (testSegment->done()) {
      continue;
    }
    allDone = false;
    return testSegment->undoneSpan();
  } while ((testSegment = testSegment->next()));
  if (allDone) {
    fDone = true;
  }
  return nullptr;
}

Very suspicious code, but it is difficult for me to understand what is the actual error here.


EA WebKit

V547 CWE-570 Expression '!first' is always false. webmediaconstraints.cpp 302


WebString StringConstraint::ToString() const {
  ....
  bool first = true;
  for (const auto& iter : exact_) {
    if (!first)
      builder.Append(", ");
    builder.Append('"');
    builder.Append(iter);
    builder.Append('"');
  }
  ....
}

As the first variable is always true, the commas between items will not be added.


XNU kernel

V547 CWE-571 Expression is always true. mtrr.c 692


void
pat_init(void)
{
  boolean_t  istate;
  uint64_t  pat;

  if (!(cpuid_features() & CPUID_FEATURE_PAT))
    return;

  istate = ml_set_interrupts_enabled(FALSE);

  pat = rdmsr64(MSR_IA32_CR_PAT);
  DBG("CPU%d PAT: was 0x%016llx\n", get_cpu_number(), pat);

  /* Change PA6 attribute field to WC if required */
  if ((pat & ~(0x0FULL << 48)) != (0x01ULL << 48)) {
    mtrr_update_action(CACHE_CONTROL_PAT);
  }
  ml_set_interrupts_enabled(istate);
}

The expression pat & [0xFFF0FFFFFFFFFFFF] can not result in the value 0x0001000000000000. So, the condition is always true. And the function mtrr_update_action is always called.


RT-Thread

V547 CWE-571 Expression 'i == 0' is always true. at91_mci.c 196


static void at91_mci_init_dma_read(struct at91_mci *mci)
{
  rt_uint8_t i;
  ....
  for (i = 0; i < 1; i++)
  {
    /* Check to see if this needs filling */
    if (i == 0)
    {
      if (at91_mci_read(AT91_PDC_RCR) != 0)
      {
        mci_dbg("Transfer active in current\n");
        continue;
      }
    }
    else {
      if (at91_mci_read(AT91_PDC_RNCR) != 0)
      {
        mci_dbg("Transfer active in next\n");
        continue;
      }
    }

    length = data->blksize * data->blks;
    mci_dbg("dma address = %08X, length = %d\n",
            data->buf, length);

    if (i == 0)
    {
      at91_mci_write(AT91_PDC_RPR, (rt_uint32_t)(data->buf));
      at91_mci_write(AT91_PDC_RCR, .....);
    }
    else
    {
      at91_mci_write(AT91_PDC_RNPR, (rt_uint32_t)(data->buf));
      at91_mci_write(AT91_PDC_RNCR, .....);
    }
  }
  ....
}

Similar errors can be found in some other places:

  • V547 CWE-571 Expression 'i == 0' is always true. at91_mci.c 215

RT-Thread

V547 CWE-570 Expression 'idx < 0' is always false. fsl_flexcomm.c 133


uint32_t FLEXCOMM_GetInstance(void *base)
{
  int i;

  for (i = 0; i < FSL_FEATURE_SOC_FLEXCOMM_COUNT; i++)
  {
    if ((uint32_t)base == s_flexcommBaseAddrs[i])
    {
      return i;
    }
  }

  assert(false);
  return 0;
}

status_t FLEXCOMM_Init(void *base, FLEXCOMM_PERIPH_T periph)
{
  int idx = FLEXCOMM_GetInstance(base);

  if (idx < 0)
  {
    return kStatus_InvalidArgument;
  }
  ....
}

Similar errors can be found in some other places:

  • V547 CWE-570 Expression 'instance < 0' is always false. fsl_spi.c 82
  • V547 CWE-570 Expression 'instance < 0' is always false. fsl_spi.c 297
  • V547 CWE-570 Expression 'instance < 0' is always false. fsl_spi.c 335

RT-Thread

V547 CWE-571 Expression is always true. Probably the '&&' operator should be used here. bxcan.c 1171


#define RT_CAN_MODE_NORMAL              0
#define RT_CAN_MODE_LISEN               1
#define RT_CAN_MODE_LOOPBACK            2
#define RT_CAN_MODE_LOOPBACKANLISEN     3

static rt_err_t control(struct rt_can_device *can,
                        int cmd, void *arg)
{
  ....
  case RT_CAN_CMD_SET_MODE:
    argval = (rt_uint32_t) arg;
    if (argval != RT_CAN_MODE_NORMAL ||
        argval != RT_CAN_MODE_LISEN ||
        argval != RT_CAN_MODE_LOOPBACK ||
        argval != RT_CAN_MODE_LOOPBACKANLISEN)
    {
      return RT_ERROR;
    }
    if (argval != can->config.mode)
    {
      can->config.mode = argval;
      return bxcan_set_mode(pbxcan->reg, argval);
    }
    break;
  ....
}

Krita

V547 Expression 'j == 0' is always false. KoColorSpace.cpp 218


QPolygonF KoColorSpace::estimatedTRCXYY() const
{
  ....
  for (int j = 5; j>0; j--) {
    channelValuesF.fill(0.0);
    channelValuesF[i] = ((max / 4)*(5 - j));

    if (colorModelId().id() != "XYZA") {
      fromNormalisedChannelsValue(data, channelValuesF);
      convertPixelsTo(....);
      xyzColorSpace->normalisedChannelsValue(....);
    }

    if (j == 0) {
      colorantY = channelValuesF[1];
      if (d->colorants.size()<2) {
        d->colorants.resize(3 * colorChannelCount());
        d->colorants[i] = ....
          d->colorants[i + 1] = ....
          d->colorants[i + 2] = ....
      }
    }
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'x < 0' is always false. kis_selection_filters.cpp 334
  • V547 Expression 'y < 0' is always false. kis_selection_filters.cpp 342

Krita

V547 Expression 'n == 128' is always false. compression.cpp 110


quint32 decode_packbits(const char *src,
                        char* dst,
                        quint16 packed_len,
                        quint32 unpacked_len)
{
    qint32    n;
    ....
    while (unpack_left > 0 && pack_left > 0)
    {
        n = *src;
        src++;
        pack_left--;

        if (n == 128)
            continue;
        else if (n > 128)
            n -= 256;
        ....
    }
    ....
}

Similar errors can be found in some other places:

  • V547 Expression 'n > 128' is always false. compression.cpp 112

Krita

V547 Expression is always false. SvgTextEditor.cpp 472


void SvgTextEditor::setTextWeightDemi()
{
    if (m_textEditorWidget.richTextEdit->textCursor()
          .charFormat().fontWeight() > QFont::Normal
        && m_textEditorWidget.richTextEdit->textCursor()
           .charFormat().fontWeight() < QFont::Normal) { // <=
        setTextBold(QFont::Normal);
    } else {
        setTextBold(QFont::DemiBold);
    }
}

Krita

V547 Expression is always true. Probably the '&&' operator should be used here. KoResourceItemChooser.cpp 408


void KoResourceItemChooser::updatePreview(KoResource *resource)
{
    ....
    if (image.format() != QImage::Format_RGB32 || // <=
    image.format() != QImage::Format_ARGB32 ||    // <=
    image.format() != QImage::Format_ARGB32_Premultiplied) {

        image = image.convertToFormat(....);
    }
    ....
}

Similar errors can be found in some other places:

  • V547 Expression is always true. Probably the '&&' operator should be used here. KoSvgTextShapeMarkupConverter.cpp 1000

System Shock

V547 Expression 'len <= 0' is always true. COMPOSE.C 235


long ComposeFlat8Diff(....)
{
  ....
  len = 0;
  //  len = ....;
  //  ....
  if (len <= 0)
  {
    ....
  }
  ....
}

Azure Service Fabric

V547 CWE-570 Expression 'nwrite < 0' is always false. Unsigned type value is never < 0. File.cpp 1941


static void* ScpWorkerThreadStart(void* param)
{
  ....
  do
  {
    size_t nwrite = fwrite(ptr, 1, remaining, destfile);
    if (nwrite < 0)
    {
      pRequest->error_.Overwrite(ErrorCode::FromErrno(errno));
      break;
    }
    else
    {
      remaining -= nwrite;
      ptr += nwrite;
      pRequest->szCopied_ += nwrite;
    }
  } while (remaining != 0);
  ....
}

Azure Service Fabric

V547 CWE-571 Expression 'len >= 0' is always true. Unsigned type value is always >= 0. Types.cpp 121


size_t BIO_ctrl_pending(BIO *b);

template <typename TBuf>
TBuf BioMemToTBuf(BIO* bio)
{
  char* data = NULL;
  auto len = BIO_ctrl_pending(bio);
  Invariant(len >= 0);
  ....
}

0 A.D.

V547 CWE-570 Expression 'nbNeighb >= 2' is always false. WaterManager.cpp 581


void WaterManager::CreateWaveMeshes()
{
  ....
  int nbNeighb = 0;
  ....
  bool found = false;
  nbNeighb = 0;
  for (int p = 0; p < 8; ++p)
  {
    if (CoastalPointsSet.count(xx+around[p][0] +
                               (yy + around[p][1])*SideSize))
    {
      if (nbNeighb >= 2)
      {
        CoastalPointsSet.erase(xx + yy*SideSize);
        continue;
      }
      ++nbNeighb;
      // We've found a new point around us.
      // Move there
      xx = xx + around[p][0];
      yy = yy + around[p][1];
      indexx = xx + yy*SideSize;
      if (i == 0)
        Chain.push_back(CoastalPoint(indexx,CVector2D(xx*2,yy*2)));
      else
        Chain.push_front(CoastalPoint(indexx,CVector2D(xx*2,yy*2)));
      CoastalPointsSet.erase(xx + yy*SideSize);
      found = true;
      break;
    }
  }
  if (!found)
    endedChain = true;
  ....
}

Perl 5

V547 Expression 'RETVAL == 0' is always true. Typemap.c 710


XS_EUPXS(XS_XS__Typemap_T_SYSRET_pass);
XS_EUPXS(XS_XS__Typemap_T_SYSRET_pass)
{
  dVAR; dXSARGS;
  if (items != 0)
    croak_xs_usage(cv,  "");
  {
    SysRet  RETVAL;
#line 370 "Typemap.xs"
    RETVAL = 0;
#line 706 "Typemap.c"
    {
      SV * RETVALSV;
      RETVALSV = sv_newmortal();
      if (RETVAL != -1) {          // <=
        if (RETVAL == 0)           // <=
          sv_setpvn(RETVALSV, "0 but true", 10);
        else
          sv_setiv(RETVALSV, (IV)RETVAL);
      }
      ST(0) = RETVALSV;
    }
  }
  XSRETURN(1);
}

Qt

V547 CWE-570 Expression 'buffer[i] < '\040' && buffer[i] > '\176'' is always false. qedidparser.cpp 169


QString QEdidParser::parseEdidString(const quint8 *data)
{
    QByteArray buffer(reinterpret_cast<const char *>(data), 13);

    // Erase carriage return and line feed
    buffer = buffer.replace('\r', '\0').replace('\n', '\0');

    // Replace non-printable characters with dash
    for (int i = 0; i < buffer.count(); ++i) {
        if (buffer[i] < '\040' && buffer[i] > '\176')
            buffer[i] = '-';
    }

    return QString::fromLatin1(buffer.trimmed());
}

Qt

V547 CWE-570 Expression 'message' is always false. qwindowscontext.cpp 802


DWORD
__stdcall
FormatMessageW(
  DWORD dwFlags,
  LPCVOID lpSource,
  DWORD dwMessageId,
  DWORD dwLanguageId,
  LPWSTR lpBuffer,
  DWORD nSize,
  va_list *Arguments
);

// Re-engineered from the inline function _com_error::ErrorMessage().
// We cannot use it directly since it uses swprintf_s(), which is not
// present in the MSVCRT.DLL found on Windows XP (QTBUG-35617).
static inline QString errorMessageFromComError(const _com_error &comError)
{
  TCHAR *message = nullptr;
  FormatMessage(
    FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
    NULL, DWORD(comError.Error()), MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
    message, 0, NULL);
  if (message) {
    const QString result = QString::fromWCharArray(message).trimmed();
    LocalFree(static_cast<HLOCAL>(message));
    return result;
  }
  if (const WORD wCode = comError.WCode())
    return QString::asprintf("IDispatch error #%u", uint(wCode));
  return QString::asprintf("Unknown error 0x0%x", uint(comError.Error()));
}

Opus

V547 CWE-571 Expression 'st->mode == 1001' is always true. opus_encoder.c 1734


#define MODE_HYBRID             1001

opus_int32 opus_encode_native(....)
{
  ....
  if (st->mode == MODE_HYBRID)
  {
    int len;

    len = (ec_tell(&enc)+7)>>3;
    if (redundancy)
      len += st->mode == MODE_HYBRID ? 3 : 1;
  ....
}

Perl Compatible Regular Expressions

V547 CWE-570 Expression 'mclength != 1' is always false. pcre2_compile.c 7355


static int
compile_branch(....)
{
  uint32_t mclength;
  ....
  if (mclength == 1 || req_caseopt == 0)
  {
    firstcu = mcbuffer[0];
    firstcuflags = req_caseopt;
    if (mclength != 1)
      {
      reqcu = code[-1];
      reqcuflags = cb->req_varyopt;
      }
    }
  ....
}

Libwebsockets

V547 CWE-571 Expression 'sock.sockfd >= 0' is always true. Unsigned type value is always >= 0. libwebsockets.c 2651


typedef UINT_PTR        SOCKET;

typedef SOCKET lws_sockfd_type;

typedef union {
  lws_sockfd_type sockfd;
  lws_filefd_type filefd;
} lws_sock_file_fd_type;

LWS_EXTERN struct lws *
lws_create_adopt_udp(....)
{
  lws_sock_file_fd_type sock;
  ....
  for (rp = r; rp; rp = rp->ai_next) {
    sock.sockfd = socket(rp->ai_family, rp->ai_socktype,
             rp->ai_protocol);
    if (sock.sockfd >= 0)         // <=
      break;
  }
  ....
}

Godot Engine

V547 CWE-570 Expression 'i >= 3' is always false. csg_shape.cpp 939


CSGBrush *CSGBox::_build_brush() {
  ....
  for (int i = 0; i < 6; i++) {
    ....
    if (i < 3)
      face_points[j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1);
    else
      face_points[3 - j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1);
    ....
  }
  ....
}

Similar errors can be found in some other places:

  • V547 CWE-571 Expression 'i >= 3' is always true. csg_shape.cpp 941

Godot Engine

V547 CWE-571 Expression 'idx >= 0 || idx < 4' is always true. variant_op.cpp 2152


void Variant::set(....) {
  ....
  int idx = p_index;
  if (idx < 0)
    idx += 4;
  if (idx >= 0 || idx < 4) {
    Color *v = reinterpret_cast<Color *>(_data._mem);
    (*v)[idx] = p_value;
    valid = true;
  }
  ....
}

Similar errors can be found in some other places:

  • V547 CWE-571 Expression 'idx >= 0 || idx < 4' is always true. variant_op.cpp 2527

Stellarium

V547 Expression 'updatePos' is always true. StelGuiItems.cpp 831


void BottomStelBar::updateText(bool updatePos)
{
  ....
  updatePos = true;
  ....
  if (location->text() != newLocation || updatePos)
  {
    updatePos = true;
    ....
  }
  ....
  if (fov->text() != str)
  {
    updatePos = true;
    ....
  }
  ....
  if (fps->text() != str)

  {
    updatePos = true;
    ....
  }

  if (updatePos)
  {
    ....
  }
}

LibrePCB

V547 CWE-571 Expression 'content' is always true. html.c 162


static int
rndr_emphasis(hoedown_buffer *ob, const hoedown_buffer *content,
              const hoedown_renderer_data *data)
{
  if (!content || !content->size) return 0;
  HOEDOWN_BUFPUTSL(ob, "<em>");
  if (content) hoedown_buffer_put(ob, content->data, content->size);
  HOEDOWN_BUFPUTSL(ob, "</em>");
  return 1;
}

LibrePCB

V547 CWE-571 Expression 'e->OutIdx >= 0' is always true. clipper.cpp 2983


void Clipper::DoMaxima(TEdge *e)
{
  ....
  else if( e->OutIdx >= 0 && eMaxPair->OutIdx >= 0 )
  {
    if (e->OutIdx >= 0) AddLocalMaxPoly(e, eMaxPair, e->Top);
    DeleteFromAEL(e);
    DeleteFromAEL(eMaxPair);
  }
  ....
}

LibrePCB

V547 CWE-571 Expression 'layer' is always true. footprintpreviewgraphicsitem.cpp 177


void FootprintPreviewGraphicsItem::paint(....) noexcept {
  ....
  for (const Circle& circle : mFootprint.getCircles()) {
    layer = mLayerProvider.getLayer(*circle.getLayerName());
    if (!layer) continue;
    if (layer){
      pen = QPen(....);
      painter->setPen(pen);
    } else
      painter->setPen(Qt::NoPen);
    ....
  }
  ....
}

Windows Calculator

V547 Expression 'm_resolvedName == L"en-US"' is always false. To compare strings you should use wcscmp() function. Calculator LocalizationSettings.h 180


wchar_t m_resolvedName[LOCALE_NAME_MAX_LENGTH];

Platform::String^ GetEnglishValueFromLocalizedDigits(....) const
{
  if (m_resolvedName == L"en-US")
  {
    return ref new Platform::String(localizedString.c_str());
  }
  ....
}

FreeRDP

V547 Expression '!pipe->In' is always false. MessagePipe.c 63


wMessagePipe* MessagePipe_New()
{
  ....
  pipe->In = MessageQueue_New(NULL);
  if (!pipe->In)
    goto error_in;

  pipe->Out = MessageQueue_New(NULL);
  if (!pipe->In)
    goto error_out;
  ....
}

FreeRDP

V547 Expression 'strcat(target, source) != NULL' is always true. triostr.c 425


TRIO_PUBLIC_STRING int
trio_append
TRIO_ARGS2((target, source),
     char *target,
     TRIO_CONST char *source)
{
  assert(target);
  assert(source);

  return (strcat(target, source) != NULL);
}

FreeRDP

V547 Expression 'cache' is always true. glyph.c 730


typedef struct rdp_glyph_cache rdpGlyphCache;

struct rdp_glyph_cache
{
  ....
  GLYPH_CACHE glyphCache[10];
  ....
};

void glyph_cache_free(rdpGlyphCache* glyphCache)
{
  ....
  GLYPH_CACHE* cache = glyphCache->glyphCache;

  if (cache)
  {
    ....
  }
  ....
}

FreeRDP

V547 Expression 'rdp->state >= CONNECTION_STATE_ACTIVE' is always true. connection.c 1489


int rdp_server_transition_to_state(rdpRdp* rdp, int state)
{
  ....
  switch (state)
  {
    ....
    case CONNECTION_STATE_ACTIVE:
      rdp->state = CONNECTION_STATE_ACTIVE;
      ....
      if (rdp->state >= CONNECTION_STATE_ACTIVE)
      {
        IFCALLRET(client->Activate, client->activated, client);

        if (!client->activated)
          return -1;
      }
    ....
  }
  ....
}

FreeRDP

V547 Expression 'status == 0x00090314' is always false. ntlm.c 299


BOOL ntlm_authenticate(rdpNtlm* ntlm, BOOL* pbContinueNeeded)
{
  ....
  if (status != SEC_E_OK)
  {
    ....
    return FALSE;
  }

  if (status == SEC_I_COMPLETE_NEEDED)            // <=
    status = SEC_E_OK;
  else if (status == SEC_I_COMPLETE_AND_CONTINUE) // <=
    status = SEC_I_CONTINUE_NEEDED;
  ....
}

rdesktop

V547 Expression 'write_time' is always false. disk.c 805


RD_NTSTATUS
disk_set_information(....)
{
  time_t write_time, change_time, access_time, mod_time;
  ....
  if (write_time || change_time)
    mod_time = MIN(write_time, change_time);
  else
    mod_time = write_time ? write_time : change_time; // <=
  ....
}

rdesktop

V547 Expression is always true. Probably the '&&' operator should be used here. disk.c 1419


static RD_NTSTATUS
disk_device_control(RD_NTHANDLE handle, uint32 request, STREAM in,
      STREAM out)
{
  ....
  if (((request >> 16) != 20) || ((request >> 16) != 9))
    return RD_STATUS_INVALID_PARAMETER;
  ....
}

LLVM/Clang

V547 [CWE-571] Expression 'nextByte != 0x90' is always true. X86DisassemblerDecoder.cpp 379


static int readPrefixes(struct InternalInstruction* insn) {
  ....
  uint8_t byte = 0;
  uint8_t nextByte;
  ....
  if (byte == 0xf3 && (nextByte == 0x88 || nextByte == 0x89 ||
                       nextByte == 0xc6 || nextByte == 0xc7)) {
    insn->xAcquireRelease = true;
    if (nextByte != 0x90) // PAUSE instruction support
      break;
  }
  ....
}

Haiku Operation System

V547 Expression 'error == ((int) 0)' is always true. Directory.cpp 688


int32
BDirectory::CountEntries()
{
  status_t error = Rewind();
  if (error != B_OK)
    return error;
  int32 count = 0;
  BPrivate::Storage::LongDirEntry entry;
  while (error == B_OK) {
    if (GetNextDirents(&entry, sizeof(entry), 1) != 1)
      break;
    if (strcmp(entry.d_name, ".") != 0 && strcmp(entry.d_name, "..") != 0)
      count++;
  }
  Rewind();
  return (error == B_OK ? count : error);
}

Haiku Operation System

V547 Expression 'remaining < 0' is always false. Unsigned type value is never < 0. DwarfFile.cpp 1947


status_t
DwarfFile::_UnwindCallFrame(....)
{
  ....
  uint64 remaining = lengthOffset + length - dataReader.Offset();
  if (remaining < 0)
    return B_BAD_DATA;
  ....
}

Haiku Operation System

V547 Expression 'sleep((unsigned) secs) < 0' is always false. Unsigned type value is never < 0. misc.cpp 56


status_t
snooze(bigtime_t amount)
{
  if (amount <= 0)
    return B_OK;

  int64 secs = amount / 1000000LL;
  int64 usecs = amount % 1000000LL;
  if (secs > 0) {
    if (sleep((unsigned)secs) < 0)     // <=
      return errno;
  }

  if (usecs > 0) {
    if (usleep((useconds_t)usecs) < 0)
      return errno;
  }

  return B_OK;
}

extern unsigned int sleep (unsigned int __seconds); extern int usleep (__useconds_t __useconds);


PPSSPP

V547 Expression 'leftvol >= 0' is always true. sceAudio.cpp 120


static u32 sceAudioOutputPannedBlocking
             (u32 chan, int leftvol, int rightvol, u32 samplePtr) {
  int result = 0;
  // For some reason, this is the only one that checks for negative.
  if (leftvol > 0xFFFF || rightvol > 0xFFFF || leftvol < 0 || rightvol < 0) {
    ....
  } else {
    if (leftvol >= 0) {
      chans[chan].leftVolume = leftvol;
    }
    if (rightvol >= 0) {
      chans[chan].rightVolume = rightvol;
    }
    chans[chan].sampleAddress = samplePtr;
    result = __AudioEnqueue(chans[chan], chan, true);
  }
}

PPSSPP

V547 Expression 'size == 8' is always false. syn-att.c 195


extern void ud_translate_att(
  int size = 0;
  .... // Variable "size" doesn't change
  if (size == 8) {
    ud_asmprintf(u, "b");
  } else if (size == 16) {
    ud_asmprintf(u, "w");
  } else if (size == 64) {
    ud_asmprintf(u, "q");
  }
  ....
}

Doom 1

V547 [CWE-571] Expression 'delta < - 64' is always true. d_net.c 130


int ExpandTics (int low)
{
  int delta;
  delta = low - (maketic&0xff);

  if (delta >= -64 && delta <= 64)
    return (maketic&~0xff) + low;
  if (delta > 64)
    return (maketic&~0xff) - 256 + low;
  if (delta < -64)
    return (maketic&~0xff) + 256 + low;

  I_Error ("ExpandTics: strange value %i at maketic %i",low,maketic);
  return 0;
}

Celestia

V547 Expression '!inputFilename.empty()' is always true. makexindex.cpp 128


int main(int argc, char* argv[])
{
  if (!parseCommandLine(argc, argv) || inputFilename.empty())
  {
    Usage();
    return 1;
  }

  istream* inputFile = &cin;
  if (!inputFilename.empty())
  {
    inputFile = new ifstream(inputFilename, ios::in);
    if (!inputFile->good())
    {
      cerr << "Error opening input file " << inputFilename << '\n';
      return 1;
    }
  }
  ....
}

TON

V547 Expression 'path' is always true. fift-main.cpp 136


int main(int argc, char* const argv[]) {
  ....
  if (!no_env) {
    const char* path = std::getenv("FIFTPATH");
    if (path) {
      parse_include_path_set(path ? path : "/usr/lib/fift",
                             source_include_path);
    }
  }
  ....
}

Kodi

V547 Expression 'lastsector' is always false. udf25.cpp:636


int udf25::UDFGetAVDP( struct avdp_t *avdp)
{
  ....
  uint32_t lastsector;
  ....
  lastsector = 0;
  ....
  for(;;) {
    ....
    if( lastsector ) {
      lbnum = lastsector;
      terminate = 1;
    } else {
      //! @todo Find last sector of the disc (this is optional).
      if( lastsector )
        lbnum = lastsector - 256;
      else
        return 0;
    }
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'lastsector' is always false. udf25.cpp:644

Kodi

V547 Expression 'values.size() != 2' is always false. GUIControlSettings.cpp:1174


bool CGUIControlRangeSetting::OnClick()
{
  ....
  std::vector<CVariant> values;
  SettingConstPtr listDefintion = settingList->GetDefinition();
  switch (listDefintion->GetType())
  {
    case SettingType::Integer:
      values.push_back(m_pSlider->
             GetIntValue(CGUISliderControl::RangeSelectorLower));
      values.push_back(m_pSlider->
             GetIntValue(CGUISliderControl::RangeSelectorUpper));
      break;
    case SettingType::Number:
      values.push_back(m_pSlider->
         GetFloatValue(CGUISliderControl::RangeSelectorLower));
      values.push_back(m_pSlider->
         GetFloatValue(CGUISliderControl::RangeSelectorUpper));
      break;
    default:
      return false;
  }
  if (values.size() != 2)
    return false;
  SetValid(CSettingUtils::SetList(settingList, values));
  return IsValid();
}

Kodi

V547 Expression 'prio == 0x7fffffff' is always true. DBusReserve.cpp:57


bool CDBusReserve::AcquireDevice(const std::string& device)
{
  ....
  int prio = INT_MAX;
  ....
  res =
    dbus_bus_request_name(
      m_conn,
      service.c_str(),
      DBUS_NAME_FLAG_DO_NOT_QUEUE |
      (prio == INT_MAX ? 0 : DBUS_NAME_FLAG_ALLOW_REPLACEMENT), // <=
      error);
  ....
}

ROOT

V547 Expression '!file_name_value.empty()' is always false. SelectionRules.cxx 1423


bool SelectionRules::AreAllSelectionRulesUsed() const {
  for(auto&& rule : fClassSelectionRules){
    ....
    std::string file_name_value;
    if (!rule.GetAttributeValue("file_name", file_name_value))
     file_name_value.clear();

    if (!file_name_value.empty()) {                  // <=
      // don't complain about defined_in rules
      continue;
    }

    const char* attrName = nullptr;
    const char* attrVal = nullptr;
    if (!file_name_value.empty()) {                  // <=
      attrName = "file name";
      attrVal = file_name_value.c_str();
    } else {
      attrName = "class";
      if (!name.empty()) attrVal = name.c_str();
    }
    ROOT::TMetaUtils::Warning(0,"Unused %s rule: %s\n", attrName, attrVal);
  }
  ....
}

Heawei Ark Compiler

V547 Expression 'idx >= 0' is always true. Unsigned type value is always >= 0. lexer.h 129


char GetCharAtWithLowerCheck(uint32 idx) const {
  return idx >= 0 ? line[idx] : 0;
}

SDCC

V547 [CWE-570] Expression 'segnib >= 0xE000' is always false. inst_r2k.cc 42


u32_t  rabbit_mmu::logical_addr_to_phys( u16_t logical_addr ) {
  u32_t  phys_addr = logical_addr;
  unsigned     segnib = logical_addr >> 12;

  if (segnib >= 0xE000)
  {
    phys_addr += ((u32_t)xpc) << 12;
  }
  ....
}

Zephyr

V547 [CWE-570] Expression 'len < 0' is always false. Unsigned type value is never < 0. keys.c 312


static int keys_set(const char *name, size_t len_rd, settings_read_cb read_cb,
        void *cb_arg)
{
  ....
  size_t len;
  ....
  len = read_cb(cb_arg, val, sizeof(val));
  if (len < 0) {
    BT_ERR("Failed to read value (err %zu)", len);
    return -EINVAL;
  }
  ....
}

Zephyr

V547 [CWE-570] Expression '(end - * p) < 1' is always false. x509_crt.c 635


static int x509_get_subject_alt_name( unsigned char **p,
                                      const unsigned char *end,
                                      mbedtls_x509_sequence *subject_alt_name )
{
  ....
  while( *p < end )
  {
    if( ( end - *p ) < 1 )
      return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
              MBEDTLS_ERR_ASN1_OUT_OF_DATA );
    ....
  }
  ....
}

Zephyr

V547 [CWE-571] Expression 'disp' is always true. lv_disp.c 148


uint32_t lv_disp_get_inactive_time(const lv_disp_t * disp)
{
  if(!disp) disp = lv_disp_get_default();
  if(!disp) {
    LV_LOG_WARN("lv_disp_get_inactive_time: no display registered");
    return 0;
  }

  if(disp) return lv_tick_elaps(disp->last_activity_time);

  lv_disp_t * d;
  uint32_t t = UINT32_MAX;
  d          = lv_disp_get_next(NULL);
  while(d) {
    t = LV_MATH_MIN(t, lv_tick_elaps(d->last_activity_time));
    d = lv_disp_get_next(d);
  }

  return t;
}

Newton Game Dynamics

V547 Expression 'axisCount' is always false. MultiBodyCar.cpp 650


void UpdateDriverInput(dVehicle* const vehicle, dFloat timestep)
{
  ....
  int axisCount = scene->GetJoystickAxis(axis);
  axisCount = 0;
  if (axisCount)
  {
    ....
  }
  ....
}

ORCT2

V547 [CWE-570] Expression 'name == nullptr' is always false. libopenrct2 ServerList.cpp 102


std::optional<ServerListEntry> ServerListEntry::FromJson(....)
{
  auto name = json_object_get(server, "name");
  ....
  if (name == nullptr || version == nullptr)
  {
    ....
  }
  else
  {
    ....
    entry.name = (name == nullptr ? "" : json_string_value(name));
    ....
  }
  ....
}

Minetest

V547 Expression 'nearest_emergefull_d == - 1' is always true. clientiface.cpp 363


void RemoteClient::GetNextBlocks (....)
{
  ....
  s32 nearest_emergefull_d = -1;
  ....
  s16 d;
  for (d = d_start; d <= d_max; d++) {
    ....
      if (block == NULL || surely_not_found_on_disk || block_is_invalid) {
        if (emerge->enqueueBlockEmerge(peer_id, p, generate)) {
          if (nearest_emerged_d == -1)
            nearest_emerged_d = d;
        } else {
          if (nearest_emergefull_d == -1) // <=
            nearest_emergefull_d = d;
          goto queue_full_break;
        }
  ....
  }
  ....
queue_full_break:
  if (nearest_emerged_d != -1) { // <=
    new_nearest_unsent_d = nearest_emerged_d;
  } else ....
}

The value nearest_emergefull_d is never changing in the loop.


PMDK

V547 [CWE-570] Expression 'rel_wait < 0' is always false. Unsigned type value is never < 0. os_thread_windows.c 359


static DWORD
get_rel_wait(const struct timespec *abstime)
{
  struct __timeb64 t;
  _ftime64_s(&t);
  time_t now_ms = t.time * 1000 + t.millitm;
  time_t ms = (time_t)(abstime->tv_sec * 1000 +
    abstime->tv_nsec / 1000000);

  DWORD rel_wait = (DWORD)(ms - now_ms);

  return rel_wait < 0 ? 0 : rel_wait;
}

PMDK

V547 [CWE-571] Expression 'blocks[i]' is always true. heap.c 1054


static struct memory_block
heap_coalesce(struct palloc_heap *heap,
  const struct memory_block *blocks[], int n)
{
  struct memory_block ret = MEMORY_BLOCK_NONE;

  const struct memory_block *b = NULL;
  ret.size_idx = 0;
  for (int i = 0; i < n; ++i) {
    if (blocks[i] == NULL)
      continue;
    b = b ? b : blocks[i];
    ret.size_idx += blocks[i] ? blocks[i]->size_idx : 0;
  }
  ....
}

Qemu

V547 Expression 'ret < 0' is always false. qcow2-cluster.c 1557


static int handle_dependencies(....)
{
  ....
  if (end <= old_start || start >= old_end) {
    ....
  } else {

    if (bytes == 0 && *m) {
      ....
      return 0;
    }

    if (bytes == 0) {
      ....
      return -EAGAIN;
    }
  ....
  }
  return 0;
}

int qcow2_alloc_cluster_offset(BlockDriverState *bs, ....)
{
  ....
  ret = handle_dependencies(bs, start, &cur_bytes, m);
  if (ret == -EAGAIN) {
    ....
  } else if (ret < 0) {
    ....
  }
}

clipp

V547 Expression 's[0] == '-'' is always false. clipp.h 303


inline bool
fwd_to_unsigned_int(const char*& s)
{
  if(!s) return false;
  for(; std::isspace(*s); ++s);
  if(!s[0] || s[0] == '-') return false;
  if(s[0] == '-') return false;
  return true;
}

Dlib

V547 Expression 'event_thread_started == false' is always true. gui_core_kernel_1.cpp 162


class event_handler_thread : public threaded_object
{
  ....
  bool event_thread_started;
  ....
};

void start_event_thread ()
{
  ....
  if (event_thread_started == false)
  {
    auto_mutex M(window_table.get_mutex());
    if (event_thread_started == false)
    {
      event_thread_started = true;
      // start up the event handler thread
      start();
  ....
}

Dlib

V547 Expression 'samples.size() > 0' is always true. svm.h 360


template <
    typename detection_type,
    typename label_type
    >
bool is_track_association_problem (
  const std::vector<std::vector<
    labeled_detection<detection_type,label_type> > >& samples
)
{
  if (samples.size() == 0)
    return false;

  unsigned long num_nonzero_elements = 0;
  for (unsigned long i = 0; i < samples.size(); ++i)
  {
    if (samples.size() > 0)
      ++num_nonzero_elements;
  }
  if (num_nonzero_elements < 2)
    return false;
  ....
}

Espressif IoT Development Framework

V547 Expression is always false. linenoise.c 256


static int getColumns(void) {
  ....
  /* Restore position. */
  if (cols > start) {
    char seq[32];
    snprintf(seq,32,"\x1b[%dD",cols-start);
    if (fwrite(seq, 1, strlen(seq), stdout) == -1) {
      /* Can't recover... */
    }
    flushWrite();
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression is always false. linenoise.c 481
  • V547 Expression is always false. linenoise.c 569

Espressif IoT Development Framework

V547 Expression is always false. linenoise.c 596


int linenoiseEditInsert(struct linenoiseState *l, char c) {
  ....
  if (fwrite(&c,1,1,stdout) == -1) return -1;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression is always false. linenoise.c 742

Espressif IoT Development Framework

V547 Expression is always false. linenoise.c 828


static int linenoiseEdit(char *buf, size_t buflen, const char *prompt)
  ....
  while(1) {
    ....
    if (fread(seq+2, 1, 1, stdin) == -1) break;
    ....
  }
  ....
}

Espressif IoT Development Framework

V547 Expression 'ret != 0' is always false. sdio_slave.c 394


esp_err_t sdio_slave_start(void)
{
  ....
  critical_exit_recv();
  ret = ESP_OK;
  if (ret != ESP_OK) return ret;

  sdio_slave_hal_set_ioready(context.hal, true);
  return ESP_OK;
}

Espressif IoT Development Framework

V547 Expression is always true. essl_sdio.c 209


esp_err_t essl_sdio_init(void *arg, uint32_t wait_ms)
{
  ....
  // Set block sizes for functions 1 to given value (default value = 512).
  if (ctx->block_size > 0 || ctx->block_size <= 2048) {
    bs = ctx->block_size;
  } else {
    bs = 512;
  }
  ....
}

Most likely this is what should be written here: ctx->block_size > 0 && ctx->block_size <= 2048


Espressif IoT Development Framework

V547 Expression 'depth <= 0' is always false. panic_handler.c 169


static void print_backtrace(const void *f, int core)
{
  XtExcFrame *frame = (XtExcFrame *) f;
  int depth = 100;
  //Initialize stk_frame with first frame of stack
  esp_backtrace_frame_t stk_frame =
    {.pc = frame->pc, .sp = frame->a1, .next_pc = frame->a0};
  panic_print_str("\r\nBacktrace:");
  print_backtrace_entry(esp_cpu_process_stack_pc(stk_frame.pc), stk_frame.sp);

  //Check if first frame is valid
  bool corrupted =
    !(esp_stack_ptr_is_sane(stk_frame.sp) &&
      (esp_ptr_executable((void *)esp_cpu_process_stack_pc(stk_frame.pc)) ||
       /* Ignore the first corrupted PC in case of InstrFetchProhibited */
       frame->exccause == EXCCAUSE_INSTR_PROHIBITED));

  //Account for stack frame that's already printed
  uint32_t i = ((depth <= 0) ? INT32_MAX : depth) - 1;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'xAlreadyYielded == ((BaseType_t) 0)' is always true. event_groups.c 260
  • V547 Expression 'xAlreadyYielded == ((BaseType_t) 0)' is always true. tasks.c 1475
  • V547 Expression 'xAlreadyYielded == ((BaseType_t) 0)' is always true. tasks.c 1520

Espressif IoT Development Framework

V547 Expression is always false. tasks.c 896


#ifndef portPRIVILEGE_BIT
  #define portPRIVILEGE_BIT ( ( UBaseType_t ) 0x00 )
#endif

static void prvInitialiseNewTask(...., UBaseType_t uxPriority, ....)
{
  StackType_t *pxTopOfStack;
  UBaseType_t x;

  #if (portNUM_PROCESSORS < 2)
  xCoreID = 0;
  #endif

  #if( portUSING_MPU_WRAPPERS == 1 )
    /* Should the task be created in privileged mode? */
    BaseType_t xRunPrivileged;
    if( ( uxPriority & portPRIVILEGE_BIT ) != 0U )
    {
      xRunPrivileged = pdTRUE;
    }
    else
    {
      xRunPrivileged = pdFALSE;
    }
  ....
}

Espressif IoT Development Framework

V547 Expression 'err != 0' is always false. sdio_slave_hal.c 96


static esp_err_t sdio_ringbuf_send(....)
{
  uint8_t* get_ptr = ....;
  esp_err_t err = ESP_OK;
  if (copy_callback) {
    (*copy_callback)(get_ptr, arg);
  }
  if (err != ESP_OK) return err;

  buf->write_ptr = get_ptr;
  return ESP_OK;
}

Espressif IoT Development Framework

V547 Expression 'bit_len == 32' is always false. spi_flash_ll.h 371


static inline void spi_flash_ll_set_usr_address(spi_dev_t *dev, uint32_t addr,
                                                int bit_len)
{
  // The blank region should be all ones
  if (bit_len >= 32) {
    dev->addr = addr;
    dev->slv_wr_status = UINT32_MAX;
  } else {
    uint32_t padding_ones = (bit_len == 32? 0 : UINT32_MAX >> bit_len);
    dev->addr = (addr << (32 - bit_len)) | padding_ones;
  }
}

Espressif IoT Development Framework

V547 Expression 'b' is always true. wpabuf.c 235


struct wpabuf * wpabuf_concat(struct wpabuf *a, struct wpabuf *b)
{
  struct wpabuf *n = NULL;
  size_t len = 0;

  if (b == NULL)
    return a;

  if (a)
    len += wpabuf_len(a);
  if (b)
    len += wpabuf_len(b);

  n = wpabuf_alloc(len);
  if (n) {
    if (a)
      wpabuf_put_buf(n, a);
    if (b)
      wpabuf_put_buf(n, b);
  }

  wpabuf_free(a);
  wpabuf_free(b);

  return n;
}

Similar errors can be found in some other places:

  • V547 Expression 'b' is always true. wpabuf.c 242

GTK

V547 [CWE-571] Expression 'max_size > 0' is always true. gtkrecentmanager.c 480


static void
gtk_recent_manager_real_changed (GtkRecentManager *manager)
{
  ....
  int age;
  int max_size = MAX_LIST_SIZE;
  ....
  .... // Variable max_size is not used here.
  ....
  if (age == 0 || max_size == 0 || !enabled)
  {
    g_bookmark_file_free (priv->recent_items);
    priv->recent_items = g_bookmark_file_new ();
    priv->size = 0;
  }
  else
  {
    if (age > 0)
      gtk_recent_manager_clamp_to_age (manager, age);
    if (max_size > 0)
      gtk_recent_manager_clamp_to_size (manager, max_size);
  }
  ....
}

GTK

V547 [CWE-571] Expression 'desktop_startup_id' is always true. gdk.c 176


static void
stash_desktop_startup_notification_id (void)
{
  const char *desktop_startup_id;

  desktop_startup_id = g_getenv ("DESKTOP_STARTUP_ID");
  if (desktop_startup_id && *desktop_startup_id != '\0')
    {
      if (!g_utf8_validate (desktop_startup_id, -1, NULL))
        g_warning ("DESKTOP_STARTUP_ID contains invalid UTF-8");
      else
        startup_notification_id =
          g_strdup (desktop_startup_id ? desktop_startup_id : "");
    }
  g_unsetenv ("DESKTOP_STARTUP_ID");
}

Open Asset Import Library

V547 [CWE-571] Expression 'extraBytes > 0' is always true. FBXUtil.cpp 224


std::string EncodeBase64(const char* data, size_t length)
{
    // calculate extra bytes needed to get a multiple of 3
    size_t extraBytes = 3 - length % 3;

    // number of base64 bytes
    size_t encodedBytes = 4 * (length + extraBytes) / 3;

    std::string encoded_string(encodedBytes, '=');

    // read blocks of 3 bytes
    for (size_t ib3 = 0; ib3 < length / 3; ib3++)
    {
        const size_t iByte = ib3 * 3;
        const size_t iEncodedByte = ib3 * 4;
        const char* currData = &data[iByte];

        EncodeByteBlock(currData, encoded_string, iEncodedByte);
    }

    // if size of data is not a multiple of 3,
    // also encode the final bytes (and add zeros where needed)
    if (extraBytes > 0)
    {
        char finalBytes[4] = { 0,0,0,0 };
        memcpy(&finalBytes[0], &data[length - length % 3], length % 3);

        const size_t iEncodedByte = encodedBytes - 4;
        EncodeByteBlock(&finalBytes[0], encoded_string, iEncodedByte);

        // add '=' at the end
        for (size_t i = 0; i < 4 * extraBytes / 3; i++)
            encoded_string[encodedBytes - i - 1] = '=';
    }
    return encoded_string;
}

Qt

V547 [CWE-571] Expression '(general_purpose_bits & Utf8Names) != 0' is always true. qzip.cpp 716


enum GeneralPurposeFlag {
  ....
  Utf8Names = 0x0800,
  ....
};

static inline void writeUShort(uchar *data, ushort i)
{
  data[0] = i & 0xff;
  data[1] = (i>>8) & 0xff;
}

void QZipWriterPrivate::addEntry(EntryType type, const QString &fileName, ....)
{
  ....
  ushort general_purpose_bits = Utf8Names; // always use utf-8
  writeUShort(header.h.general_purpose_bits, general_purpose_bits);

  const bool inUtf8 = (general_purpose_bits & Utf8Names) != 0;
  header.file_name = inUtf8 ? fileName.toUtf8() : fileName.toLocal8Bit();
}

Qt

V547 [CWE-571] Expression 'vi < 0' is always true. qtreeview.cpp 2219


QModelIndex QTreeView::moveCursor(....)
{
  ....
  int vi = -1;
  if (vi < 0)
    vi = qMax(0, d->viewIndex(current));
  ....
}

Qt

V547 [CWE-570] Expression 'type == - 1' is always false. qv4datacollector.cpp 282


int QV4DataCollector::encodeScopeType(
  QV4::Heap::ExecutionContext::ContextType scopeType)
{
    switch (scopeType) {
    case QV4::Heap::ExecutionContext::Type_GlobalContext:
        break;
    case QV4::Heap::ExecutionContext::Type_WithContext:
        return 2;
    case QV4::Heap::ExecutionContext::Type_CallContext:
        return 1;
    case QV4::Heap::ExecutionContext::Type_QmlContext:
        return 3;
    case QV4::Heap::ExecutionContext::Type_BlockContext:
        return 4;
    }
    return 0;
}

QJsonObject QV4DataCollector::buildFrame(....)
{
  ....
  for (int i = 0, ei = scopeTypes.count(); i != ei; ++i) {
    int type = encodeScopeType(scopeTypes[i]);
    if (type == -1)
      continue;

    QJsonObject scope;
    scope[QLatin1String("index")] = i;
    scope[QLatin1String("type")] = type;
    scopes.push_back(scope);
  }
  ....
}

Qt

V547 [CWE-570] Expression 'l != len' is always false. qv4typedarray.cpp 306


typedef unsigned int uint;

ReturnedValue TypedArrayCtor::virtualCallAsConstructor(....)
{
  ....
  qint64 l = argc ? argv[0].toIndex() : 0;
  if (scope.engine->hasException)
    return Encode::undefined();
  // ### lift UINT_MAX restriction
  if (l < 0 || l > UINT_MAX)
    return scope.engine->throwRangeError(QLatin1String("Index out of range."));
  uint len = (uint)l;
  if (l != len)
    scope.engine->throwRangeError(
      QStringLiteral("Non integer length for typed array."));
  ....
}

Qt

V547 [CWE-570] Expression 'count == 9' is always false. qfont.cpp 2142


bool QFont::fromString(const QString &descrip)
{
  ....
  const int count = l.count();
  if (!count || (count > 2 && count < 9) || count == 9 || count > 17 ||
      l.first().isEmpty()) {
    qWarning("QFont::fromString: Invalid description '%s'",
             descrip.isEmpty() ? "(empty)" : descrip.toLatin1().data());
    return false;
  }

  setFamily(l[0].toString());
  if (count > 1 && l[1].toDouble() > 0.0)
    setPointSizeF(l[1].toDouble());
  if (count == 9) {                            // <=
    setStyleHint((StyleHint) l[2].toInt());
    setWeight(QFont::Weight(l[3].toInt()));
    setItalic(l[4].toInt());
    setUnderline(l[5].toInt());
    setStrikeOut(l[6].toInt());
    setFixedPitch(l[7].toInt());
  } else if (count >= 10) { .... }
}

Qt

V547 [CWE-571] Expression 'lang' is always true. qfontconfigdatabase.cpp 462


// this could become a list of all languages used for each writing
// system, instead of using the single most common language.
static const char languageForWritingSystem[][6] = {
    "",     // Any
    "en",  // Latin
    "el",  // Greek
    "ru",  // Cyrillic

    ...... // No null pointers. Empty string literals are used.

    "", // Symbol
    "sga", // Ogham
    "non", // Runic
    "man" // N'Ko
};
static_assert(sizeof languageForWritingSystem /
        sizeof *languageForWritingSystem == QFontDatabase::WritingSystemsCount);

static void populateFromPattern(....)
{
  ....
  for (int j = 1; j < QFontDatabase::WritingSystemsCount; ++j) {
    const FcChar8 *lang = (const FcChar8*) languageForWritingSystem[j];
    if (lang) {
      FcLangResult langRes = FcLangSetHasLang(langset, lang);
      if (langRes != FcLangDifferentLang) {
  ....
}

Qt

V547 [CWE-571] Expression 'socket != - 1' is always true. qnativesocketengine_unix.cpp 315


bool QNativeSocketEnginePrivate::createNewSocket(....)
{
  ....
  int socket = qt_safe_socket(domain, type, protocol, O_NONBLOCK);
  ....
  if (socket < 0) {
    ....
    return false;
  }

  socketDescriptor = socket;

  if (socket != -1) {
    this->socketProtocol = socketProtocol;
    this->socketType = socketType;
  }
  return true;
}

Qt

V547 [CWE-571] Expression 'current' is always true. qopenglframebufferobject.cpp 1185


bool QOpenGLFramebufferObject::release()
{
  if (!isValid())
    return false;

  QOpenGLContext *current = QOpenGLContext::currentContext();
  if (!current)
    return false;

  Q_D(QOpenGLFramebufferObject);
#ifdef QT_DEBUG
  ....
#endif

  if (current) {
    d->funcs.glBindFramebuffer(GL_FRAMEBUFFER,
                               current->defaultFramebufferObject());

    QOpenGLContextPrivate *contextPrv = QOpenGLContextPrivate::get(current);
    contextPrv->qgl_current_fbo_invalid = true;
    contextPrv->qgl_current_fbo = nullptr;
  }

  return true;
}

Qt

V547 [CWE-571] Expression 'window != m_window' is always true. qquick3dscenemanager.cpp 60


void QQuick3DSceneManager::setWindow(QQuickWindow *window)
{
  if (window == m_window)
    return;

  if (window != m_window) {
    if (m_window)
      disconnect(....);
    m_window = window;
    connect(....);
    emit windowChanged();
  }
}

Qt

V547 [CWE-570] Expression '!count' is always false. qsqltablemodel.cpp 1110


bool QSqlTableModel::removeRows(int row, int count, const QModelIndex &parent)
{
  Q_D(QSqlTableModel);
  if (parent.isValid() || row < 0 || count <= 0)
    return false;
  else if (row + count > rowCount())
    return false;
  else if (!count)
    return true;
  ....
}

Qt

V547 [CWE-571] Expression 'widgetItem' is always true. qdockarealayout.cpp 1167


bool QDockAreaLayoutInfo::insertGap(....)
{
  ....
  QDockAreaLayoutItem new_item
    = widgetItem == nullptr
      ? QDockAreaLayoutItem(subinfo)
      : widgetItem ? QDockAreaLayoutItem(widgetItem)
                   : QDockAreaLayoutItem(placeHolderItem);
  ....
}

Qt

V547 [CWE-571] Expression 'identifierWithEscapeChars' is always true. qqmljslexer.cpp 817


int Lexer::scanToken()
{
  ....
  bool identifierWithEscapeChars = false;
  ....
  if (!identifierWithEscapeChars) {
    identifierWithEscapeChars = true;
    ....
  }
  ....
  if (identifierWithEscapeChars) {
    ....
  }
  ....
}

Qt

V547 [CWE-571] Expression 'softwareRenderer' is always true. qsgsoftwarethreadedrenderloop.cpp 510


void QSGSoftwareRenderThread::syncAndRender()
{
  ....
  bool canRender = wd->renderer != nullptr;

  if (canRender) {
     auto softwareRenderer = static_cast<QSGSoftwareRenderer*>(wd->renderer);
     if (softwareRenderer)
       softwareRenderer->setBackingStore(backingStore);
  ....
}

Most likely this is what should be written here: dynamic_cast<QSGSoftwareRenderer*>(wd->renderer);


Qt

V547 [CWE-570] Expression 'm_verbose' is always false. qmlprofilerapplication.cpp 495


void QmlProfilerApplication::tryToConnect()
{
  Q_ASSERT(!m_connection->isConnected());
  ++ m_connectionAttempts;

  if (!m_verbose && !(m_connectionAttempts % 5)) {// print every 5 seconds
    if (m_verbose) {
      if (m_socketFile.isEmpty())
        logError(
          QString::fromLatin1("Could not connect to %1:%2 for %3 seconds ...")
          .arg(m_hostName).arg(m_port).arg(m_connectionAttempts));
      else
        logError(
          QString::fromLatin1("No connection received on %1 for %2 seconds ...")
          .arg(m_socketFile).arg(m_connectionAttempts));
    }
  }
  ....
}

Qt

V547 [CWE-571] Expression 'month' is always true. qdatetime.cpp 4907


static const char qt_shortMonthNames[][4] = {
    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

static int fromShortMonthName(QStringView monthName)
{
  for (unsigned int i = 0;
       i < sizeof(qt_shortMonthNames) / sizeof(qt_shortMonthNames[0]); ++i)
  {
    if (monthName == QLatin1String(qt_shortMonthNames[i], 3))
      return i + 1;
  }
  return -1;
}

QDateTime QDateTime::fromString(QStringView string, Qt::DateFormat format)
{
  ....
  month = fromShortMonthName(parts.at(1));
  if (month)
    day = parts.at(2).toInt(&ok);

  // If failed, try day then month
  if (!ok || !month || !day) {
    month = fromShortMonthName(parts.at(2));
    if (month) {
      QStringView dayPart = parts.at(1);
      if (dayPart.endsWith(u'.'))
        day = dayPart.chopped(1).toInt(&ok);
    }
  }
  ....
}

Similar errors can be found in some other places:

  • V547 [CWE-571] Expression 'month' is always true. qdatetime.cpp 4913

Free Heroes of Might and Magic II

V547 Expression 'palette.empty()' is always true. image_tool.cpp 32


const std::vector<uint8_t> PALPAlette()
{
  std::vector<uint8_t> palette;
  if (palette.empty())
  {
    palette.resize( 256 * 3 );
    for ( size_t i = 0; i < palette.size(); ++i )
    {
      palette[i] = kb_pal[i] << 2;
    }
  }
  return palette;
}

Snort

V547 Expression 'rval != - 6' is always true. output_base.c 219


static int register_module(....)
{
  ....
  int rval;
    if ((rval = register_plugin(current_dm)) != OUTPUT_SUCCESS)
    {
      if (rval != OUTPUT_ERROR_EXISTS)
        fprintf(stderr, "%s: Failed to register OUTPUT plugin.\n",
  current_dm->name);
      return OUTPUT_ERROR;
    }
  ....
}

static int register_plugin(const Output_Module_t *dm)
{
  if (....)
  {
    ....
    return OUTPUT_ERROR;
  }
  ....
  return OUTPUT_SUCCESS;
}

#define OUTPUT_SUCCESS 0
#define OUTPUT_ERROR -1
#define OUTPUT_ERROR_EXISTS -6

Snort

V547 Expression 'ret == - 2' is always false. base.c 344


static void load_static_modules(void)
{
  ....
  ret = output_load_module(dirpath);
  if (ret == OUTPUT_SUCCESS)
  {
    DEBUG_WRAP(DebugMessage(DEBUG_INIT, "Found module %s\n", de->d_name););
  }
  else if (ret == OUTPUT_ERROR_NOMEM)
  {
    closedir(dirp);
    return OUTPUT_ERROR_NOMEM;
  }
  ....
}

Snort

V547 Expression 'found_offset' is always true. sf_snort_plugin_pcre.c 202


static int pcre_test(...., int *found_offset)
{
  ....
  *found_offset = -1;
  ....

  if (found_offset)
  {
    *found_offset = ovector[1];
    ....
  }
  return matched;
}

Snort

V547 Expression 'sipMsg->status_code > 0' is always true. sip_dialog.c 806


int SIP_updateDialog(SIPMsg *sipMsg, SIP_DialogList *dList, SFSnortPacket *p)
{
  int ret;
  ....
  if (sipMsg->status_code == 0)
    ret = SIP_processRequest(....);
  else if (sipMsg->status_code > 0)
    ret = SIP_processResponse(....);
  else
    ret = SIP_FAILURE;
  ....
}

xlang

V547 [CWE-570] Expression 'padding == 0' is always false. database.h 505.


static uint32_t stream_offset(std::string_view const& name) noexcept
{
    uint32_t padding = 4 - name.size() % 4;

    if (padding == 0)
    {
        padding = 4;
    }

    return static_cast<uint32_t>(8 + name.size() + padding);
}

Darwin-XNU

V547 Expression 'bp->nb_dirtyoff >= bp->nb_dirtyend' is always false. nfs_bio.c 3858


int
nfs_vinvalbuf_internal(....)
{
  struct nfsbuf *bp;
  ....
  off_t end = ....;

  /* check for any dirty data before the EOF */
  if ((bp->nb_dirtyend > 0) && (bp->nb_dirtyoff < end))
  {
    /* clip dirty range to EOF */
    if (bp->nb_dirtyend > end)
    {
      bp->nb_dirtyend = end;

      if (bp->nb_dirtyoff >= bp->nb_dirtyend)             // <=
      {
        bp->nb_dirtyoff = bp->nb_dirtyend = 0;
      }
    }

    if ((bp->nb_dirtyend > 0) && (bp->nb_dirtyoff < end)) // <=
    {
      ....
    }
  }
  ....
}

Darwin-XNU

V547 Expression 'ar->k_ar.ar_arg_mac_string == NULL' is always true. audit_mac.c 246


void
audit_arg_mac_string(struct kaudit_record *ar, ....)
{
  if (ar->k_ar.ar_arg_mac_string == NULL)
  {
    ar->k_ar.ar_arg_mac_string = kheap_alloc(....);
  }
  ....
  if (ar->k_ar.ar_arg_mac_string == NULL)
  {
    if (ar->k_ar.ar_arg_mac_string == NULL)
    {
      return;
    }
  }
  ....
}

Darwin-XNU

V547 Expression '(value & (1ULL << 62)) == 1' is always false. vm_shared_region.c 2820


static kern_return_t
vm_shared_region_slide_page_v3(vm_offset_t vaddr, ....)
{
  ....
  uint8_t *page_content = (uint8_t *)vaddr;
  uint16_t page_entry;
  ....
  uint8_t* rebaseLocation = page_content;
  uint64_t delta = page_entry;
  do {
    rebaseLocation += delta;
    uint64_t value;
    memcpy(&value, rebaseLocation, sizeof(value));
    ....
    bool isBind = (value & (1ULL << 62)) == 1;   // <=
    if (isBind) {
      return KERN_FAILURE;
    }
    ....
  } while (delta != 0);
  ....
}

Storm Engine

V547 Expression 'nStringCode >= 0xffffff' is always false. dstring_codec.h 84


#define DHASH_SINGLESYM 255
....
uint32_t Convert(const char *pString, ....)
{
  uint32_t nStringCode;
  ....
  nStringCode = ((((unsigned char)pString[0]) << 8) & 0xffffff00) |
                  (DHASH_SINGLESYM)
  ....
  if (nStringCode >= 0xffffff)
  {
    __debugbreak();
  }
  return nStringCode;
}

LLVM/Clang

V547 [CWE-570] Expression 'pathname_.c_str() == nullptr' is always false. gtest-filepath.cc 349


std::string pathname_;
....
void FilePath::Normalize() {
  if (pathname_.c_str() == nullptr) {
    pathname_ = "";
    return;
  }
....
}

DuckStation

V547 Expression 'i < pathLength' is always true. file_system.cpp 454


void CanonicalizePath(const char *Path, ....)
{
  ....
  u32 pathLength = static_cast<u32>(std::strlen(Path));
  ....
  for (i = 0; i < pathLength;)
  {
    ....
    char nextCh = (i < pathLength) ? Path[i + 1] : '\0';
    ....
  }
  ....
}

DuckStation

V547 Expression 'm_value.wSecond <= other.m_value.wSecond' is always true. timestamp.cpp 311


bool Timestamp::operator<=(const Timestamp& other) const
{
  ....
  if (m_value.wYear > other.m_value.wYear)
    return false;
  else if (m_value.wYear < other.m_value.wYear)
    return true;
  if (m_value.wMonth > other.m_value.wMonth)
    return false;
  else if (m_value.wMonth < other.m_value.wMonth)
    return true;
  if (m_value.wDay > other.m_value.wDay)
    return false;
  else if (m_value.wDay < other.m_value.wDay)
    return true;
  if (m_value.wHour > other.m_value.wHour)
    return false;
  else if (m_value.wHour < other.m_value.wHour)
    return true;
  if (m_value.wMinute > other.m_value.wMinute)
    return false;
  else if (m_value.wMinute < other.m_value.wMinute)
    return true;
  if (m_value.wSecond > other.m_value.wSecond)
    return false;
  else if (m_value.wSecond <= other.m_value.wSecond)
    return true;
  if (m_value.wMilliseconds > other.m_value.wMilliseconds)
    return false;
  else if (m_value.wMilliseconds < other.m_value.wMilliseconds)
    return true;

  return false;
}

RPCS3

V547 Expression 'rawcode == CELL_KEYC_KPAD_NUMLOCK' is always false. cellKb.cpp 126


enum Keys
{
  // ....
  CELL_KEYC_KPAD_NUMLOCK          = 0x53,
  // ....
};

u16 cellKbCnvRawCode(u32 arrange, u32 mkey, u32 led, u16 rawcode)
{
  // ....

  // CELL_KB_RAWDAT
  if (rawcode <= 0x03
      || rawcode == 0x29
      || rawcode == 0x35
      || (rawcode >= 0x39 && rawcode <= 0x53)    // <=
      || rawcode == 0x65
      || rawcode == 0x88
      || rawcode == 0x8A
      || rawcode == 0x8B)
  {
    return rawcode | 0x8000;
  }

  const bool is_alt = mkey & (CELL_KB_MKEY_L_ALT | CELL_KB_MKEY_R_ALT);
  const bool is_shift = mkey & (CELL_KB_MKEY_L_SHIFT | CELL_KB_MKEY_R_SHIFT);
  const bool is_caps_lock = led & (CELL_KB_LED_CAPS_LOCK);
  const bool is_num_lock = led & (CELL_KB_LED_NUM_LOCK);

  // CELL_KB_NUMPAD

  if (is_num_lock)
  {
    if (rawcode == CELL_KEYC_KPAD_NUMLOCK)  return 0x00 | 0x4000; // <=
    if (rawcode == CELL_KEYC_KPAD_SLASH)    return 0x2F | 0x4000;
    if (rawcode == CELL_KEYC_KPAD_ASTERISK) return 0x2A | 0x4000;
    if (rawcode == CELL_KEYC_KPAD_MINUS)    return 0x2D | 0x4000;
    if (rawcode == CELL_KEYC_KPAD_PLUS)     return 0x2B | 0x4000;
    if (rawcode == CELL_KEYC_KPAD_ENTER)    return 0x0A | 0x4000;
    if (rawcode == CELL_KEYC_KPAD_0)        return 0x30 | 0x4000;
    if (rawcode >= CELL_KEYC_KPAD_1 && rawcode <= CELL_KEYC_KPAD_9)
      return (rawcode - 0x28) | 0x4000;
  }
}

RPCS3

V547 Expression 'current_version < threshold_version' is always false. Unsigned type value is never < 0. device.cpp 91


void physical_device::create(VkInstance context,
                             VkPhysicalDevice pdev,
                             bool allow_extensions)
{
  else if (get_driver_vendor() == driver_vendor::NVIDIA)
  {
#ifdef _WIN32
    // SPIRV bugs were fixed in 452.28 for windows
    const u32 threshold_version = (452u >> 22) | (28 >> 14);
#else
    // SPIRV bugs were fixed in 450.56 for linux/BSD
    const u32 threshold_version = (450u >> 22) | (56 >> 14);
#endif
    // Clear patch and revision fields
    const auto current_version = props.driverVersion & ~0x3fffu;
    if (current_version < threshold_version)
    {
      rsx_log.error(....);
    }
  }
}

CARLA

V547 Expression 'm_trail == 0' is always false. unpack.hpp 699


std::size_t m_trail;
....
inline int context::execute(const char* data, std::size_t len,
 std::size_t& off)
{
  ....
  case MSGPACK_CS_EXT_8: {
                uint8_t tmp;
                load<uint8_t>(tmp, n);
                m_trail = tmp + 1;
                if(m_trail == 0) {
                    unpack_ext(m_user, n, m_trail, obj);
                    int ret = push_proc(obj, off);
                    if (ret != 0) return ret;
                }
                else {
                    m_cs = MSGPACK_ACS_EXT_VALUE;
                    fixed_trail_again = true;
                }
            } break;
  ....
}

CARLA

V547 Expression '(uint8) WheelLocation >= 0' is always true. Unsigned type value is always >= 0. CARLAWheeledVehicle.cpp 510


float ACarlaWheeledVehicle::GetWheelSteerAngle(
  EVehicleWheelLocation WheelLocation) {

  check((uint8)WheelLocation >= 0)
  check((uint8)WheelLocation < 4)
  ....
}

CARLA

V547 Expression 'rounds > 1' is always true. CarlaExporter.cpp 137


void FCarlaExporterModule::PluginButtonClicked()
{
  ....
  int rounds;
  rounds = 5;
  ....
  for (int round = 0; round < rounds; ++round)
  {
    for (UObject* SelectedObject : BP_Actors)
    {
      ....
      // check to export in this round or not
      if (rounds > 1)                                          // <=
      {
        if (areaType == AreaType::BLOCK && round != 0)
          continue;
        else if (areaType == AreaType::ROAD && round != 1)
          continue;
        else if (areaType == AreaType::GRASS && round != 2)
          continue;
        else if (areaType == AreaType::SIDEWALK && round != 3)
          continue;
        else if (areaType == AreaType::CROSSWALK && round != 4)
          continue;
      }
      ....
    }
  }
}

TheXTech

V547 Expression 'NPC[A].Type == 54 && NPC[A].Type == 15' is always false. Probably the '||' operator should be used here. thextech npc_update.cpp 1277


else if(
     NPC[A].Type == 21 || NPC[A].Type == 22 || NPC[A].Type == 25
  || NPC[A].Type == 26 || NPC[A].Type == 31 || NPC[A].Type == 32
  || NPC[A].Type == 238 || NPC[A].Type == 239 || NPC[A].Type == 35
  || NPC[A].Type == 191 || NPC[A].Type == 193
  || (NPC[A].Type == 40 && NPC[A].Projectile == true) || NPC[A].Type == 49
  || NPC[A].Type == 58 || NPC[A].Type == 67 || NPC[A].Type == 68
  || NPC[A].Type == 69 || NPC[A].Type == 70
  || (NPCIsVeggie[NPC[A].Type] && NPC[A].Projectile == false)
  || (NPC[A].Type == 29 && NPC[A].Projectile == true)

  ||    (NPC[A].Projectile == true
     && (NPC[A].Type == 54 && NPC[A].Type == 15))            // <=

  || .... )
{ .... }

TheXTech

V547 Expression 'A == 48' is always false. thextech effect.cpp 1652


else if(A == 16) // Dead Giant Bullet Bill
{
  numEffects++;
  Effect[numEffects].Shadow = Shadow;
  ....
  Effect[numEffects].Location.SpeedY = Location.SpeedY;
  Effect[numEffects].Location.SpeedX = Location.SpeedX;
  if(A == 48)                                          // <=
    Effect[numEffects].Location.SpeedY = -8;
  Effect[numEffects].Life = 120;
  Effect[numEffects].Type = A;
}

TheXTech

V547 Expression 'tempPlayer == 0' is always true. thextech blocks.cpp 576


// don't spawn players from blocks anymore
tempPlayer = 0;
if(tempPlayer == 0) // Spawn the npc
{
  numNPCs++; // create a new NPC
  NPC[numNPCs].Active = true;
  NPC[numNPCs].TimeLeft = 1000;
....

Chromium

V547 Expression 'entry_size > 0' is always true. objects-printer.cc 1195


void FeedbackVector::FeedbackVectorPrint(std::ostream& os)
{
  ....
  FeedbackMetadataIterator iter(metadata());
  while (iter.HasNext()) {
    ....
    int entry_size = iter.entry_size();
    if (entry_size > 0) os << " {";         // <=
    for (int i = 0; i < entry_size; i++)
    {
      ....
    }
    if (entry_size > 0) os << "\n  }";      // <=
  }
  os << "\n";
}

int FeedbackMetadataIterator::entry_size() const
{
  return FeedbackMetadata::GetSlotSize(kind());
}

int FeedbackMetadata::GetSlotSize(FeedbackSlotKind kind) {
  switch (kind) {
    case FeedbackSlotKind::kForIn:
    ....
      return 1;

    case FeedbackSlotKind::kCall:
    ....
      return 2;

    case FeedbackSlotKind::kInvalid:
    ....
      UNREACHABLE();
  }
  return 1;
}

Blend2D

V547 Expression 'h == 0' is always false. jpegcodec.cpp 252


BLResult blJpegDecoderImplProcessMarker(....) noexcept {
  uint32_t h = blMemReadU16uBE(p + 1);
  // ....
  if (h == 0)
    return blTraceError(BL_ERROR_JPEG_UNSUPPORTED_FEATURE);
  // ....
  impl->delayedHeight = (h == 0); // <=
  // ....
}

static void blPngDeinterlaceBits(....) noexcept {
  // ....
  uint32_t x = w;
  // ....
  switch (n) {
    case 2: {
      // ....
      if (x <= 4) break;
      if (x >= 5) b = uint32_t(*d5++);
      // ....
    }
  // ....
  }
  // ....
}

MuditaOS

V547 Expression 'activeInput' is always true. ServiceAudio.cpp 250


std::optional<AudioMux::Input *> AudioMux::GetActiveInput();

....

auto Audio::handleSetVolume(....) -> std::unique_ptr<AudioResponseMessage>
{
  ....
  if (const auto activeInput = audioMux.GetActiveInput(); activeInput)
  {
    if (activeInput)
    {
      retCode = activeInput.value()->audio->SetOutputVolume(clampedValue);
    }
  }
  ....
}

MuditaOS

V547 Expression 'snoozeCount == 0' is always true. NotificationProvider.cpp 117


void NotificationProvider::handleSnooze(unsigned snoozeCount)
{
  if (snoozeCount > 0)
  {
    notifications[NotificationType::AlarmSnooze] =
       std::make_shared<notifications::AlarmSnoozeNotification>(snoozeCount);
  }
  else if (snoozeCount == 0)
  {
    notifications.erase(NotificationType::AlarmSnooze);
  }

  send();
}

MuditaOS

V547 Expression 'currentState == ButtonState::Off' is always true. ButtonOnOff.cpp 33


enum class ButtonState : bool
{
  Off,
  On
};
....
void ButtonOnOff::switchState(const ButtonState newButtonState)
{
  currentState = newButtonState;
  if (currentState == ButtonState::On)
  {
    ....
  }
  else if (currentState == ButtonState::Off)
  {
    ....
  }
}

Similar errors can be found in some other places:

  • V547 Expression 'status != 0x00' is always false. AVRCP.cpp 68
  • V547 Expression 'stream_endpoint->close_stream == 1' is always false. avdtp.c 1223
  • V547 Expression 'stream_endpoint->abort_stream == 1' is always false. avdtp.c 1256
  • And 1 additional diagnostic messages.

Ogre3D

V547 Expression 'x == 0' is always true/false. OgreTerrain.cpp 3750


Terrain::NeighbourIndex Terrain::getNeighbourIndex(long x, long y)
{
  if (x < 0)
  {
    if (y < 0)
      return NEIGHBOUR_SOUTHWEST;
    else if (y > 0)
      return NEIGHBOUR_NORTHWEST;
    else
      return NEIGHBOUR_WEST;
  }
  else if (x > 0)
  {
    if (y < 0)
      return NEIGHBOUR_SOUTHEAST;
    else if (y > 0)
      return NEIGHBOUR_NORTHEAST;
    else
      return NEIGHBOUR_EAST;
  }

  if (y < 0)
  {
    if (x == 0)               // <=
      return NEIGHBOUR_SOUTH;
  }
  else if (y > 0)
  {
    if (x == 0)               // <=
      return NEIGHBOUR_NORTH;
  }

  return NEIGHBOUR_NORTH;
}

Here the x variable is checked for 0 after false checks: x > 0 and x < 0. This check is pointless. Why checking the x variable for 0 if we can access this part of the code only if x == 0 — simple math!


Ogre3D

V547 Expression 'i != end' is always true. OgreScriptTranslator.cpp 787


bool ScriptTranslator::getMatrix4(
  AbstractNodeList::const_iterator i,
  AbstractNodeList::const_iterator end,
  Matrix4 *m)
{
  int n = 0;
  while (i != end && n < 16)
  {
    if (i != end)
    {
      Real r = 0;
      if (getReal(*i, &r))
        (*m)[n / 4][n % 4] = r;
      else
        return false;
    }
    else
    {
      return false;
    }
    ++i;
    ++n;
  }
  return true;
}

Very strange code. I notice at least two problems here: 1. The i != end condition is checked twice. If the condition in while is true, then the condition in if will always be true. The check is unnecessary. 2. The else branch is unreachable. At the same time, it returns false.


GPCS4

V547 [CWE-570] Expression 'nOldFlag & VMPF_NOACCESS' is always false. PlatMemory.cpp 22


enum VM_PROTECT_FLAG
{
  VMPF_NOACCESS  = 0x00000000,
  ....
};

inline uint32_t GetProtectFlag(....)
{
  uint32_t nNewFlag = 0;
  do
  {
    if (nOldFlag & VMPF_NOACCESS)
    {
      nNewFlag = PAGE_NOACCESS;
      break;
    }
    ....
  } while (false);
  return nNewFlag;
}

GPCS4

V547 [CWE-571] Expression 'retAddress' is always true. Memory.cpp 373


void* MemoryAllocator::allocateInternal(....)
{
  ....
  while (searchAddr < SCE_KERNEL_APP_MAP_AREA_END_ADDR)
    {
      ....
      void* retAddress = VMAllocate(reinterpret_cast<void*>(regionAddress), len,
                                    plat::VMAT_RESERVE_COMMIT, uprot);
      if (!retAddress)
      {
        searchAddr = reinterpret_cast<size_t>(mi.pRegionStart) + mi.nRegionSize;
        continue;
      }
      ....
      if (retAddress)
      {
        // unlikely
        plat::VMFree(retAddress);
      }
    ....
    }
  ....
}

GPCS4

V547 [CWE-571] Expression 'pipeConfig == kPipeConfigP16' is always true. GnmDepthRenderTarget.h 170


uint8_t getZReadTileSwizzleMask(void) const
    {
      ....
      if (pipeConfig != kPipeConfigP16 ||
        zfmt == kZFormatInvalid ||
        !GpuAddress::isMacroTiled(tileMode))
      {
        return 0;
      }

      ....
      if (pipeConfig == kPipeConfigP16)
      {
        GpuAddress::getAltNumBanks(&numBanks, tileMode,
                                   totalBitsPerElement, numFragments);
        shift = 4;
      }
      else
      {
        ....
      }
      ....
    }

Overgrowth

V547 Expression 'connect_id_ == - 1' is always true. placeholderobject.cpp 342


class PlaceholderObject
{
private:
  int connect_id_;
  ....
};

ObjectSanityState PlaceholderObject::GetSanity()
{
  ....
  if( .... && connect_id_ == -1)
  {
    if( connect_id_ == -1)
    {
      ....
    }
  }
  ....
}

Overgrowth

V547 Expression 'imageBits == 8' is always false. texture_data.cpp 305


void TextureData::GetUncompressedData(unsigned char* data)
{
  int imageBits = 32;
  ....
  if (imageBits == 8)
  {
    ....
  }
  else if (imageBits == 24)
  {
    ....
  }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'imageBits == 24' is always false. texture_data.cpp 313

LLVM/Clang

V547 [CWE-570] Expression 'FirstSemiPos == std::string::npos' is always false. UnicodeNameMappingGenerator.cpp 46


static std::unordered_multimap<char32_t, std::string>
loadDataFiles(const std::string &NamesFile, const std::string &AliasesFile) {
  ....
  auto FirstSemiPos = Line.find(';');
  if (FirstSemiPos == std::string::npos)
    continue;
  auto SecondSemiPos = Line.find(';', FirstSemiPos + 1);
  if (FirstSemiPos == std::string::npos)
    continue;
  ....
}

LLVM/Clang

V547 [CWE-570] Expression '!data_sp' is always false. Host.cpp 248


Status Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) {
  ....
  auto data_sp = StructuredData::ParseJSON(output);
  if (!data_sp) {
    error.SetErrorString("invalid JSON");
    return error;
  }

  auto dict_sp = data_sp->GetAsDictionary();
  if (!data_sp) {
    error.SetErrorString("invalid JSON");
    return error;
  }
  ....
}

VCMI

V547 Expression 'val > 1' is always false. CComponent.cpp 218


std::string CComponent::getSubtitleInternal()
{
  ....
  if (val)
    return ....;
  else
    return val > 1 ? creature->getNamePluralTranslated()
                   : creature->getNameSingularTranslated();
  ....
}

VCMI

V547 Expression 'first_block > 0' is always true. concurrent_vector.h 669


void deallocate_segment(....)
{
  ....
  if (seg_index >= first_block)
  {
    segment_element_allocator_traits::deallocate(....);
  }
  else
  if (seg_index == 0)
  {
    elements_to_deallocate = first_block > 0 ? this->segment_size(first_block)
                                             : this->segment_size(0);
    ....
  }
}

VCMI

V547 Expression 'currentAnimations.empty()' is always true. BattleStacksController.cpp 384


void BattleStacksController::updateBattleAnimations(uint32_t msPassed)
{
  ....
  if (hadAnimations && currentAnimations.empty())
  {
    //stackAmountBoxHidden.clear();
    owner.executeStagedAnimations();
    if (currentAnimations.empty())
      owner.onAnimationsFinished();
  }
  ....
}

VCMI

V547 Expression '(mask & 1) == 0' is always true. CStack.cpp 262


std::vector<BattleHex> CStack::meleeAttackHexes(....)
{
  ....
  int mask = 0;
  ....
  if (....)
  {
    if ((mask & 1) == 0)
    {
      mask |= 1;
      res.push_back(defenderPos);
    }
  }
  ....
}

GTK

V547 [CWE-570] Expression 'keysb[2] > keysa[2]' is always false. gtktreelistrowsorter.c 158


static int
gtk_tree_list_row_sort_keys_compare (gconstpointer a,
                                     gconstpointer b,
                                     gpointer      data)
{
  ....
  gpointer *keysa = (gpointer *) a;
  gpointer *keysb = (gpointer *) b;
  ....
  resa = unpack (keysa, &keysa, &sizea);
  resb = unpack (keysb, &keysb, &sizeb);
  if (!resa)
    return resb ? GTK_ORDERING_LARGER :
      (keysa[2] < keysb[2] ? GTK_ORDERING_SMALLER :
      (keysb[2] > keysa[2] ? GTK_ORDERING_LARGER : GTK_ORDERING_EQUAL));
  else if (!resb)
    return GTK_ORDERING_SMALLER;
  ....
}

Microsoft PowerToys

V547 Expression is always true. Settings.cpp 241


void FancyZonesSettings::LoadSettings()
{
  ....
  if (auto val = values.get_int_value(....))
  {
    // Avoid undefined behavior
    if (   *val >= 0
        || *val < static_cast<int>(OverlappingZonesAlgorithm::EnumElements))
    {
      auto algorithm = (OverlappingZonesAlgorithm)*val;
      if (m_settings.overlappingZonesAlgorithm != algorithm)
      {
        m_settings.overlappingZonesAlgorithm = algorithm;
        NotifyObservers(SettingId::OverlappingZonesAlgorithm);
      }
    }
  }
  ....
}

Microsoft PowerToys

V547 Expression 'placement.showCmd == 3' is always false. WindowUtils.cpp 336


....
#define SW_SHOWMINIMIZED    2
#define SW_SHOWMAXIMIZED    3
....
#define SW_MINIMIZE         6
....
#define SW_RESTORE          9
....

void FancyZonesWindowUtils::SizeWindowToRect(HWND window, RECT rect) noexcept
{
  ....
  if ((placement.showCmd != SW_SHOWMINIMIZED) &&
      (placement.showCmd != SW_MINIMIZE))
  {
    placement.showCmd = SW_RESTORE;
  }
  // Remove maximized show command to make sure
  // window is moved to the correct zone.
  if (placement.showCmd == SW_SHOWMAXIMIZED)     // <=
  {
    placement.showCmd = SW_RESTORE;
    placement.flags &= ~WPF_RESTORETOMAXIMIZED;
  }
  ....
}

Microsoft PowerToys

V547 Expression 'token_size < 0' is always false. Unsigned type value is never < 0. NtdllExtensions.cpp 314


std::wstring NtdllExtensions::pid_to_user(DWORD pid)
{
  ....
  DWORD token_size = 0;
  GetTokenInformation(token, TokenUser, nullptr, 0, &token_size);

  if (token_size < 0)
  {
    return user;
  }
  ....
}

YTsaurus

V547 Expression 'operandIndex >= 0' is always true. Unsigned type value is always >= 0. subquery.cpp:1061


std::vector<TSubquery> BuildThreadSubqueries(....)
{
  ....
  std::vector<TSubquery> subqueries;
  ....
  for (auto& stripe : subquery.StripeList->Stripes)
  {
    size_t operandIndex = stripe->GetInputStreamIndex();

    YT_VERIFY(operandIndex >= 0);
    ....
  }
  ....
}

YTsaurus

V547 Expression 'paddingSize >= 0' is always true. Unsigned type value is always >= 0. chunk_index_builder.cpp:278:1


TChunkIndexBlock BuildChunkIndexBlock( .... )
{
  ....
  for(int sectorIndex = 0;
      sectorIndex < bestFormatDetail->GetSectorCount();
      ++sectorIndex)
  {
    ....
    auto paddingSize = THashTableChunkIndexFormatDetail::SectorSize –
                         (buffer - sectorStart) - sizeof(TChecksum);
    YT_VERIFY(paddingSize >= 0);
    WriteZeroes(buffer, paddingSize);
    ....
  }
  ....
}

GZDoom

V547 Expression 'available % fuzzstep != 0' is always false. r_draw_rgba.cpp 328


void SWPalDrawers::DrawUnscaledFuzzColumn(const SpriteDrawerArgs& args)
{
  ....
  int fuzzstep = 1;
  int fuzz = _fuzzpos % FUZZTABLE;

  #ifndef ORIGINAL_FUZZ

  while (count > 0)
  {
    int available = (FUZZTABLE - fuzz);
    int next_wrap = available / fuzzstep;
    if (available % fuzzstep != 0)
      next_wrap++;
    ....
  }
  ....
}

GZDoom

V547 Expression 'c != 0x0c' is always false. pcxtexture.cpp 477


int FPCXTexture::CopyPixels(FBitmap *bmp, int conversion, int frame)
{
  ....
  uint8_t c = lump.ReadUInt8();
  c = 0x0c;  // Apparently there's many non-compliant PCXs out there...
  if (c != 0x0c)
  {
    for(int i=0;i<256;i++) pe[i]=PalEntry(255,i,i,i);// default to a gray map
  }
  ....
}

GZDoom

V547 Expression 'length < 0' is always false. Unsigned type value is never < 0. animlib.cpp 225


int32_t ANIM_LoadAnim(anim_t *anim, const uint8_t *buffer, size_t length)
{
  ....
  length -= sizeof(lpfileheader)+128+768;
  if (length < 0)
    return -1;
  ....
  length -= lpheader.nLps * sizeof(lp_descriptor);
  if (length < 0)
    return -2;
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'length < 0' is always false. Unsigned type value is never < 0. animlib.cpp 247

GZDoom

V547 Expression 'count == 1' is always false. codegen.cpp 9405


ExpEmit FxVMFunctionCall::Emit(VMFunctionBuilder *build)
{
  int count = 0;
  if (count == 1)
  {
    ExpEmit reg;
    if (CheckEmitCast(build, false, reg))
    {
      ArgList.DeleteAndClear();
      ArgList.ShrinkToFit();
      return reg;
    }
  }
  ....
}

GZDoom

V547 Expression 'dstFloatSize != srcFloatSize' is always false. x86regalloc.cpp 1115


static ASMJIT_INLINE bool X86RAPass_mustConvertSArg(X86RAPass* self,
                                                    uint32_t dstTypeId,
                                                    uint32_t srcTypeId) noexcept
{
  bool dstFloatSize = dstTypeId == TypeId::kF32   ? 4 :
                      dstTypeId == TypeId::kF64   ? 8 : 0;

  bool srcFloatSize = srcTypeId == TypeId::kF32   ? 4 :
                      srcTypeId == TypeId::kF32x1 ? 4 :
                      srcTypeId == TypeId::kF64   ? 8 :
                      srcTypeId == TypeId::kF64x1 ? 8 : 0;

  if (dstFloatSize && srcFloatSize)
    return dstFloatSize != srcFloatSize;
  else
    return false;
}

iSulad

V547 [CWE-571] Expression '(value & mask) == 0' is always true. deviceset.c 1126


static bool is_device_id_free(struct device_set *devset, int device_id)
{
    int mask = 0;
    int value = 0;
    int *value_ptr = NULL;
    int key = device_id / 8;

    mask = 1 << (device_id % 8);
    value_ptr = map_search(devset->device_id_map, &key);

    return value_ptr ? (*value_ptr & mask) == 0 : (value & mask) == 0;
}

iSulad

V547 [CWE-570] Expression 'arch_size < 0' is always false. Unsigned type value is never < 0. specs_security.c 492


static size_t docker_seccomp_arches_count(
    const char *seccomp_architecture,
    const docker_seccomp *docker_seccomp_spec)
{
  ....
  if (seccomp_architecture == NULL) {
    ERROR("Invalid input seccomp architecture");
    return -1;
  }
  ....
}

static int dup_architectures_to_oci_spec(....)
{
  ....
  size_t arch_size = 0;
  ....
  arch_size =
    docker_seccomp_arches_count(seccomp_architecture, docker_seccomp_spec);
  if (arch_size < 0) {
      ERROR("Failed to get arches count from docker seccomp spec");
      return -1;
  }
  ....
}

iSulad

V547 [CWE-570] Expression 'ret != 0' is always false. registry_apiv2.c 438


static int registry_request(....)
{
  int ret = 0;
  int sret = 0;
  ....
  ret = registry_ping(desc);
  if (ret != 0) {
     ERROR("ping failed");
     return -1;
  }

  sret = snprintf(url, sizeof(url), "%s://%s%s",
                  desc->protocol, desc->host, path);
  if (sret < 0 || (size_t)sret >= sizeof(url)) {
    ERROR("Failed to sprintf url, path is %s", path);
    ret = -1;
    goto out;
  }

  headers = util_str_array_dup((const char **)custom_headers,
                               util_array_len((const char **)custom_headers));
  if (ret != 0) {                             // <=
    ERROR("duplicate custom headers failed");
    ret = -1;
    goto out;
  }
  ....
}

This is what should have been written here: if (headers == NULL) {


Blender

V547 [CWE-570] Expression 'tot < 1' is always false. threads.cc 131


void BLI_threadpool_init(ListBase *threadbase,
                         void *(*do_thread)(void *),
                         int tot)
{
  ....
  if (threadbase != nullptr && tot > 0)
  {
    ....
    if (tot > RE_MAX_THREAD)
    {
      tot = RE_MAX_THREAD;
    }
    else if (tot < 1)
    {
      tot = 1;
    }
    ....
  }
  ....
}

Blender

V547 [CWE-570] Expression 'alignment == ALIGN_VIEW' is always false. object_add.cc 544


enum
{
  ALIGN_WORLD = 0,
  ALIGN_VIEW,
  ALIGN_CURSOR,
};

bool ED_object_add_generic_get_opts(bool *r_is_view_aligned, ....)
{
  ....
    if (RNA_struct_property_is_set(op->ptr, "rotation"))
    {
      ....
    }
    else
    {
      int alignment = ALIGN_WORLD;
      PropertyRNA *prop = RNA_struct_find_property(op->ptr, "align");

      if (RNA_property_is_set(op->ptr, prop))
      {
        *r_is_view_aligned = alignment == ALIGN_VIEW;       // <=
        alignment = RNA_property_enum_get(op->ptr, prop);
      }
    }
  ....
}

Similar errors can be found in some other places:

  • V547 Expression 'changed == false' is always true. editmesh_tools.cc 1456
  • V547 Expression 'ob->type == OB_GPENCIL_LEGACY' is always true. gpencil_edit.cc 130
  • V547 Expression 'closure_count > i' is always true. eevee_raytrace.cc 371
  • And 1 additional diagnostic messages.