Example 2.

LRESULT CALLBACK IOP_DISASM(...)

{

...

switch(LOWORD(wParam))

{

case (IDOK || IDCANCEL):

EndDialog(hDlg,TRUE);

return(TRUE);

break;

}

...

}



switch(LOWORD(wParam))

{

case IDOK: //no break

case IDCANCEL:

EndDialog(hDlg,TRUE);

return(TRUE);

break;

}



Example 3.

void projillum(short* wtab, int xdots, int ydots, double dec)

{

...

s = sin(-dtr(dec));

x = -s * sin(th);

y = cos(th);

...

lon = (y == 0 && x == 0) ? 0.0 : rtd(atan2(y, x));

}



Example 4.

int Game::DrawGLScene(void)

{

...

radius=fast_sqrt(maxdistance);

radius=110;

...

}



Example 5.

Q3TextCustomItem* Q3TextDocument::parseTable(...)

{

...

while (end < length

&& !hasPrefix(doc, length, end, QLatin1String(" && !hasPrefix(doc, length, end, QLatin1String(" && !hasPrefix(doc, length, end, QLatin1String(" && !hasPrefix(doc, length, end, QLatin1String(" && !hasPrefix(doc, length, end, QLatin1String(" && !hasPrefix(doc, length, end, QLatin1String(" && !hasPrefix(doc, length, end, QLatin1String(" && !hasPrefix(doc, length, end, QLatin1String("

...

}



Example 6.

int sf_error (SNDFILE *sndfile)

{

...

if (!sndfile)

{

if (sf_error != 0)

return sf_errno;

return 0;

} ;

...

}



Example 7.

static IppStatus mp2_HuffmanTableInitAlloc(Ipp32s *tbl, ...)

{

...

for (i = 0; i < num_tbl; i++) {

*tbl++;

}

...

}



Always true or always false conditions

Example 1.

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;

}

...

}



if ( nBytes > 3 && pBytes[0] == TCHAR(0xEF) &&

pBytes[1] == TCHAR(0xBB) &&

pBytes[2] == TCHAR(0xBF) )



Example 2.

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;

}



...

}

...

}



Example 3.

typedef unsigned short wint_t;

...

void lexungetc(wint_t c) {

if (c < 0)

return;

g_backstack.push_back(c);

}



Example 4.

static UINT_PTR m_socketHandle;



void TTrace::LoopMessages(void)

{

...

// Socket creation

if ( (m_socketHandle = socket(AF_INET,SOCK_STREAM,0)) < 0)

{

continue;

}

...

}



m_socketHandle = socket(AF_INET,SOCK_STREAM,0);



Example 5.

IdleState CalculateIdleState(...) {

...

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;

...

}



if (current_idle_time > INT_MAX)

current_idle_time = INT_MAX;



Example 6.

U_CDECL_BEGIN static const char* U_CALLCONV

_processVariableTop(...)

{

...

if(i == locElementCapacity &&

(*string != 0 || *string != '_'))

{

*status = U_BUFFER_OVERFLOW_ERROR;

}

...

}



Example 7.

bool equals( class1* val1, class2* val2 ) const{

{

...

size_t size = val1->size();

...

while ( --size >= 0 ){

if ( !comp(*itr1,*itr2) )

return false;

itr1++;

itr2++;

}

...

}



for (size_t i = 0; i != size; i++){

if ( !comp(*itr1,*itr2) )

return false;

itr1++;

itr2++;

}



Example 8.

enum enum_mysql_timestamp_type

str_to_datetime(...)

{

...

else if (str[0] != 'a' || str[0] != 'A')

continue; /* Not AM/PM */

...

}



else if (str[0] != 'a' && str[0] != 'A')



Example 9.

STDMETHODIMP QEnumPins::QueryInterface(const IID &iid,void **out)

{

...

if (S_OK)

AddRef();

return hr;

}



Example 10.

void GetWindAtSingleTornado(...)

{

...

if(radius < THRESH * 5)

*yOut = THRESH * 10 / radius;

else if (radius < THRESH * 5)

*yOut = -3.0f / (THRESH * 5.0f) *

(radius - THRESH * 5.0f) + 3.0f;

else

*yOut = 0.0f;

...

}



Example 11.

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()));

...

}



Example 12.

QStringList ProFileEvaluator::Private::values(...)

{

...

else if (ver == QSysInfo::WV_NT)

ret = QLatin1String("WinNT");

else if (ver == QSysInfo::WV_2000)

ret = QLatin1String("Win2000");

else if (ver == QSysInfo::WV_2000) <<--

ret = QLatin1String("Win2003");

else if (ver == QSysInfo::WV_XP)

ret = QLatin1String("WinXP");

...

}



Code vulnerabilities

Example 1.

char *CUT_CramMd5::GetClientResponse(LPCSTR ServerChallenge)

{

...

if (m_szPassword != NULL)

{

...

if (m_szPassword != '\0')

{

...

}



if (m_szPassword != NULL)

{

...

if (*m_szPassword != '\0')



Example 2.

bool ChromeFrameNPAPI::Invoke(...)

{

ChromeFrameNPAPI* plugin_instance =

ChromeFrameInstanceFromNPObject(header);

if (!plugin_instance &&

(plugin_instance->automation_client_.get()))

return false;

...

}



if (plugin_instance &&

(plugin_instance->automation_client_.get()))

return false;



Example 3.

void MD5::finalize () {

...

uint1 buffer[64];

...

// Zeroize sensitive information

memset (buffer, 0, sizeof(*buffer));

...

}



memset (buffer, 0, sizeof(buffer));



Example 4.

void Time::Explode(..., Exploded* exploded) const {

...

ZeroMemory(exploded, sizeof(exploded));

...

}



ZeroMemory(exploded, sizeof(*exploded));



Example 5.

#define MEMSET_BZERO(p,l) memset((p), 0, (l))



void apr__SHA256_Final(..., SHA256_CTX* context) {

...

MEMSET_BZERO(context, sizeof(context));

...

}



Example 6.

static char *_skipblank(char * str)

{

char * endstr=str+strlen(str);

while ((*str==' ' || *str=='\t') && str!='\0') str++;

while ((*endstr==' ' || *endstr=='\t') &&

endstr!='\0' && endstr endstr--;

...

}



while ((*str==' ' || *str=='\t') && *str!='\0') str++;

while ((*endstr==' ' || *endstr=='\t') &&

*endstr!='\0' && endstr endstr--;



Example 7.

png_size_t

png_check_keyword(png_structp png_ptr, png_charp key,

png_charpp new_key)

{

...

if (key_len > 79)

{

png_warning(png_ptr, "keyword length must be 1 - 79 characters");

new_key[79] = '\0';

key_len = 79;

}

...

}



(*new_key)[79] = '\0';



Example 8.

static void

wsman_set_subscribe_options(...)

{

...

if (options->delivery_certificatethumbprint ||

options->delivery_password ||

options->delivery_password) {

...

}



if (options->delivery_certificatethumbprint ||

options->delivery_username ||

options->delivery_password) {



Example 9.

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] == '

')

buf[len - indx] = 0;

++indx;

}

}

}



Example 10.

void Append( PCXSTR pszSrc, int nLength )

{

...

UINT nOldLength = GetLength();

if (nOldLength < 0)

{

// protects from underflow

nOldLength = 0;

}

...

}



Example 11.

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 {

...

}

}



Example 12.

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;

}

...

}



Example 13.

void CAST256::Base::UncheckedSetKey(const byte *userKey,

unsigned int keylength, const NameValuePairs &)

{

AssertValidKeyLength(keylength);

word32 kappa[8];

...

memset(kappa, 0, sizeof(kappa));

}



Copy-Paste

Example 1.

void* tag_write_setframe(char *tmem,

const char *tid, const string dstr)

{

...

if(lset)

{

fhead[11] = '\0';

fhead[12] = '\0';

fhead[13] = '\0';

fhead[13] = '\0';

}

...

}



Example 2.

static int rr_cmp(uchar *a,uchar *b)

{

if (a[0] != b[0])

return (int) a[0] - (int) b[0];

if (a[1] != b[1])

return (int) a[1] - (int) b[1];

if (a[2] != b[2])

return (int) a[2] - (int) b[2];

if (a[3] != b[3])

return (int) a[3] - (int) b[3];

if (a[4] != b[4])

return (int) a[4] - (int) b[4];

if (a[5] != b[5])

return (int) a[1] - (int) b[5];

if (a[6] != b[6])

return (int) a[6] - (int) b[6];

return (int) a[7] - (int) b[7];

}



return (int) a[1] - (int) b[5];



return (int) a[5] - (int) b[5];



Example 3.

BOOL GetImageHlpVersion(DWORD &dwMS, DWORD &dwLS)

{

return(GetInMemoryFileVersion(("DBGHELP.DLL"),

dwMS,

dwLS)) ;

}



BOOL GetDbgHelpVersion(DWORD &dwMS, DWORD &dwLS)

{

return(GetInMemoryFileVersion(("DBGHELP.DLL"),

dwMS,

dwLS)) ;

}



BOOL GetImageHlpVersion(DWORD &dwMS, DWORD &dwLS)

{

return(GetInMemoryFileVersion(("IMAGEHLP.DLL"),

dwMS,

dwLS)) ;

}



Example 4.

MapTy PerPtrTopDown;

MapTy PerPtrBottomUp;



void clearBottomUpPointers() {

PerPtrTopDown.clear();

}



void clearTopDownPointers() {

PerPtrTopDown.clear();

}



void clearBottomUpPointers() {

PerPtrBottomUp.clear();

}



Example 5.

bool qt_testCollision(...)

{

...

t=x1; x1=x2; x2=t;

t=y1; x1=y2; y2=t;

...

}



t=x1; x1=x2; x2=t;

t=y1; y1=y2; y2=t;



Example 6.

inline_ bool Contains(const LSS& lss)

{

return Contains(Sphere(lss.mP0, lss.mRadius)) &&

Contains(Sphere(lss.mP0, lss.mRadius));

}



Example 7.

void KeyWordsStyleDialog::updateDlg()

{

...

Style & w1Style =

_pUserLang->_styleArray.getStyler(STYLE_WORD1_INDEX);

styleUpdate(w1Style, _pFgColour[0], _pBgColour[0],

IDC_KEYWORD1_FONT_COMBO, IDC_KEYWORD1_FONTSIZE_COMBO,

IDC_KEYWORD1_BOLD_CHECK, IDC_KEYWORD1_ITALIC_CHECK,

IDC_KEYWORD1_UNDERLINE_CHECK);



Style & w2Style =

_pUserLang->_styleArray.getStyler(STYLE_WORD2_INDEX);

styleUpdate(w2Style, _pFgColour[1], _pBgColour[1],

IDC_KEYWORD2_FONT_COMBO, IDC_KEYWORD2_FONTSIZE_COMBO,

IDC_KEYWORD2_BOLD_CHECK, IDC_KEYWORD2_ITALIC_CHECK,

IDC_KEYWORD2_UNDERLINE_CHECK);



Style & w3Style =

_pUserLang->_styleArray.getStyler(STYLE_WORD3_INDEX);

styleUpdate(w3Style, _pFgColour[2], _pBgColour[2],

IDC_KEYWORD3_FONT_COMBO, IDC_KEYWORD3_FONTSIZE_COMBO,

IDC_KEYWORD3_BOLD_CHECK, IDC_KEYWORD3_BOLD_CHECK,

IDC_KEYWORD3_UNDERLINE_CHECK);



Style & w4Style =

_pUserLang->_styleArray.getStyler(STYLE_WORD4_INDEX);

styleUpdate(w4Style, _pFgColour[3], _pBgColour[3],

IDC_KEYWORD4_FONT_COMBO, IDC_KEYWORD4_FONTSIZE_COMBO,

IDC_KEYWORD4_BOLD_CHECK, IDC_KEYWORD4_ITALIC_CHECK,

IDC_KEYWORD4_UNDERLINE_CHECK);

...

}



styleUpdate(...

IDC_KEYWORD1_BOLD_CHECK, IDC_KEYWORD1_ITALIC_CHECK,

...);

styleUpdate(...

IDC_KEYWORD2_BOLD_CHECK, IDC_KEYWORD2_ITALIC_CHECK,

...);

styleUpdate(...

IDC_KEYWORD3_BOLD_CHECK, IDC_KEYWORD3_BOLD_CHECK, <<--

...);

styleUpdate(...

IDC_KEYWORD4_BOLD_CHECK, IDC_KEYWORD4_ITALIC_CHECK,

...);



Example 8.

void CardButton::DrawRect(HDC hdc, RECT *rect, bool fNormal)

{

...

HPEN hhi = CreatePen(0, 0, MAKE_PALETTERGB(crHighlight));

HPEN hsh = CreatePen(0, 0, MAKE_PALETTERGB(crShadow));

...

if(fNormal)

hOld = SelectObject(hdc, hhi);

else

hOld = SelectObject(hdc, hhi);

...

}



if(fNormal)

hOld = SelectObject(hdc, hhi);

else

hOld = SelectObject(hdc, hsh);



Example 9.

Status VC1VideoDecoder::ResizeBuffer()

{

...

if(m_pContext && m_pContext->m_seqLayerHeader &&

m_pContext->m_seqLayerHeader->heightMB &&

m_pContext->m_seqLayerHeader->heightMB)

...

}



if(m_pContext && m_pContext->m_seqLayerHeader &&

m_pContext->m_seqLayerHeader->heightMB &&

m_pContext->m_seqLayerHeader->widthMB)



Example 10.

BOOL APIENTRY

GreStretchBltMask(...)

{

...

MaskPoint.x += DCMask->ptlDCOrig.x;

MaskPoint.y += DCMask->ptlDCOrig.x;

...

}



MaskPoint.x += DCMask->ptlDCOrig.x;

MaskPoint.y += DCMask->ptlDCOrig.y;



Late check of null pointers

Example 1.

void Item_Paint(itemDef_t *item) {

vec4_t red;

menuDef_t *parent = (menuDef_t*)item->parent;

red[0] = red[3] = 1;

red[1] = red[2] = 0;

if (item == NULL) {

return;

}

...

}



Example 2.

static int

check_vbr_header(PMPSTR mp, int bytes)

{

...

buf = buf->next;

pos = buf->pos;

if(!buf) return -1; /* fatal error */

...

}



Example 3.

static long i_stage2_each(root_block *root,

v_fragment *v, void(*callback)(long,int))

{

cdrom_paranoia *p=v->p;

long dynoverlap=p->dynoverlap/2*2;

if (!v || !v->one) return(0);

...

}



Example 4.

bool OnCheck(Player* player, Unit* /*target*/)

{

bool checkArea =

player->GetAreaId() == AREA_ARGENT_TOURNAMENT_FIELDS ||

player->GetAreaId() == AREA_RING_OF_ASPIRANTS ||

player->GetAreaId() == AREA_RING_OF_ARGENT_VALIANTS ||

player->GetAreaId() == AREA_RING_OF_ALLIANCE_VALIANTS ||

player->GetAreaId() == AREA_RING_OF_HORDE_VALIANTS ||

player->GetAreaId() == AREA_RING_OF_CHAMPIONS;



return player && checkArea && player->duel &&

player->duel->isMounted;

}

The error has been found with rule : The 'player' pointer was utilized before it was verified against nullptr. Check lines: 310, 312. scripts achievement_scripts.cpp 310



Miscellaneous

Example 1.

inline

void elxLuminocity(const PixelRGBus& iPixel,

LuminanceCell< PixelRGBus >& oCell)

{

oCell._luminance = uint16(0.2220f*iPixel._red +

0.7067f*iPixel._blue + 0.0713f*iPixel._green);

oCell._pixel = iPixel;

}



inline

void elxLuminocity(const PixelRGBi& iPixel,

LuminanceCell< PixelRGBi >& oCell)

{

oCell._luminance = 2220*iPixel._red +

7067*iPixel._blue + 0713*iPixel._green;

oCell._pixel = iPixel;

}



Example 2.

JERRCODE CJPEGDecoder::DecodeScanBaselineNI(void)

{

...

for(c = 0; c < m_scan_ncomps; c++)

{

block = m_block_buffer + (DCTSIZE2*m_nblock*(j+(i*m_numxMCU)));



// skip any relevant components

for(c = 0; c < m_ccomp[m_curr_comp_no].m_comp_no; c++)

{

block += (DCTSIZE2*m_ccomp[c].m_nblocks);

}

...

}



Example 3.

static ID_INLINE int BigLong(int l)

{ LongSwap(l); }



Example 4.

int Notepad_plus::getHtmlXmlEncoding(....) const

{

...

if (langT != L_XML && langT != L_HTML && langT == L_PHP)

return -1;

...

}



if (langT != L_XML && langT != L_HTML && langT != L_PHP)



References



PVS-Studio Main Product Page. http://www.viva64.com/en/pvs-studio/

Download the fully functional trial. http://www.viva64.co...tudio-download/

Buy PVS-Studio. http://www.viva64.com/en/order/

PVS-Studio Documentation. http://www.viva64.com/en/d/

Feedback. http://www.viva64.co...about-feedback/

Twitter. http://twitter.com/Code_Analysis



< 0).Pc Ps2 Emulator project. Incorrect switch.The error was found through the V560 diagnostic: A part of conditional expression is always true: 2. pcsx2 debugger.cpp 321This code does not have any meaning. The programmer must have intended to write it this way:CPU Identifying Tool project. A too strict condition.The error was found through the V550 diagnostic: An odd precise comparison: x == 0. It's probably better to use a comparison with defined precision: fabs(A - B) 'V519 diagnostic: The 'radius' object is assigned values twice successively. Perhaps this is a mistake. Lugaru gamedraw.cpp 1505The programmer must have deliberately written value 110 into the 'radius' variable for the sake of experiment and then forgot to remove this line. As a result, we have a meaningless and maybe even invalid code.QT project. Duplicated check.The error was found through the V501 diagnostic: There are identical sub-expressions to the left and to the right of the '&&' operator. Qt3Support q3richtext.cpp 6978Presence of the "Audacity project. Strange check.The error was found through the V516 diagnostic: Consider inspecting an odd expression. Non-null function pointer is compared to null: 'sf_error != 0'. libsndfile sndfile.c 491The "sf_error != 0" check always returns true, since 'sf_error' is the name of the function in which the code is executed.IPP Samples project. Strange code inside a loop.The error was found through the V532 diagnostic: Consider inspecting the statement of '*pointer++' pattern. Probably meant: '(*pointer)++'. mpeg2_dec umc_mpeg2_dec.cpp 59The loop body is probably incomplete because it is meaningless in the current form.It is a very large and widely-spread type of errors. These errors also vary greatly depending on the importance level. To non-dangerous errors we may refer incorrect conditions in ASSERT that actually do not check anything. To dangerous errors, incorrect checks of buffer size or index size are referred.Shareaza project. Value range of char type.The error was found through the V547 diagnostic: Expression 'pBytes [ 0 ] == 0xEF' is always false. The value range of signed char type: [-128, 127]. Shareaza remote.cpp 350In this code, the 'TCHAR' type is the 'char' type. The value range of char is from -128 to 127 inclusive. Value 0xEF in the variable of the char type is nothing else than number -17. When comparing the char variable with number 0xEF, its type is extended up to the 'int' type. But the value still lies inside the range [-128..127]. The "pBytes[0] == 0xEF" ("-17 == 0xEF") condition is always false, and the program does not work as intended.This is the correct comparison:TortoiseSVN project. Value range of char type.The error was found through the V547 diagnostic: Expression '* utf8CheckBuf == 0xC0' is always false. The value range of signed char type: [-128, 127]. tortoiseblame.cpp 310While the defect in the previous example seems to be caused through mere inattention, in this case it is not so. Here is another identical example where a condition is always false. This is a very widely-spread type of errors in various projects.VirtualDub project. Unsigned type is always >= 0.The error was found through the V547 diagnostic: Expression 'c < 0' is always false. Unsigned type value is never < 0. Ami lexer.cpp 225The "c < 0" condition is always false because the variable of the unsigned type is always above or equal to 0.Swiss-Army Knife of Trace project. Socket handling.The error was found through the V547 diagnostic: Expression '(m_socketHandle = socket (2, 1, 0)) < 0' is always false. Unsigned type value is never < 0. Vs8_Win_Lib tracetool.cpp 871An attempt to check that a socket was created successfully is performed incorrectly. If a socket cannot be created, this situation is not handled in any way. To make the check work correctly, we should use the INVALID_SOCKET constant:Chromium project. Time handling.The error was found through the V547 diagnostic: Expression 'current_idle_time < 0' is always false. Unsigned type value is never < 0. browser idle_win.cc 23To handle time, a variable of the unsigned type is used. As a result, check of too large values does not work. This is the correct code:ICU project. Error in condition.The error was found through the V547 diagnostic: Expression '*string != 0 || *string != '_'' is always true. Probably the '&&' operator should be used here. icui18n ucol_sit.cpp 242The condition contains a logical error. The "(*string != 0 || *string != '_')" subexpression is always true. It is impossible that one and the same string character is not equal to 0 and '_' at a time.QT project. Dangerous loop.The error was found through the V547 diagnostic: Expression '--size >= 0' is always true. Unsigned type value is always >= 0. QtCLucene arrays.h 154The (--size >= 0) condition is always true, since the size variable has the unsigned type. It means that if two sequences being compared are alike, we will get an overflow that will in its turn cause Access Violation or other program failures.This is the correct code:MySQL project. Error in condition.The error was found through the V547 diagnostic: Expression 'str [0] != 'a' || str [0] != 'A'' is always true. Probably the '&&' operator should be used here. clientlib my_time.c 340The condition is always true because the character is always either not equal to 'a' or to 'A'. This is the correct check:QT project. Incorrect count of references.The error was found through the V545 diagnostic: Such conditional expression of 'if' operator is incorrect for the HRESULT type value '(HRESULT) 0L'. The SUCCEEDED or FAILED macro should be used instead. phonon_ds9 qbasefilter.cpp 60The check condition is represented by the S_OK constant. Since S_OK is 0, the AddRef() function will never be called. This is how this check must look: if (hr == S_OK).TickerTape project. Incorrect tornado.The error was found through the V517 diagnostic: The use of 'if (A) {...} else if (A) {...}' pattern was detected. There is a probability of logical error presence. TickerTape wind.cpp 118The second condition is always false. The reason is that the first condition coincides with the second. There must be a misprint here.Apache HTTP Server project. Error of socket handling in Windows.The error was found through the V547 diagnostic: Expression 'csd < 0' is always false. Unsigned type value is never < 0. libhttpd child.c 404Socket handling errors very often emerge in crossplatform programs built under Windows. In Linux, socket descriptors are represented by the signed type, while in Windows it is the unsigned type. Programmers often forget about this and check the error status by comparing the value to 0. This is incorrect; you must use specialized constants.QT project. Misprint in comparisons.The error was found through the V517 diagnostic: The use of 'if (A) {...} else if (A) {...}' pattern was detected. There is a probability of logical error presence. Check lines: 2303, 2305. lrelease profileevaluator.cpp 2303In the string we have marked, there must be the text "ver == QSysInfo::WV_2003". Because of this error, the "ret = QLatin1String("Win2003")" statement will never be executed.Of course, errors leading to code vulnerabilities are actually misprints, incorrect conditions and incorrect array handling. But we decided to single out certain errors into a separate group because they relate to the notion of software vulnerabilities. An intruder, using such errors, can try to disturb program operation, perform an attack to gain extended rights or carry out any other actions he/she needs.Ultimate TCP/IP project. Incorrect check of an empty string.The error was found through the V528 diagnostic: It is odd that pointer to 'char' type is compared with the '\0' value. Probably meant: *m_szPassword != '\0'. UTMail ut_crammd5.cpp 333This code fragment must check that the pointer to the password is not equal to NULL and that the string is not empty. But instead, the code checks twice that the pointer is not equal to NULL. The check of the string does not work. The "if (m_szPassword != '\0')" condition was intended to check that there is a terminal null in the very beginning of the string, which means that the string is empty. But a pointer dereferencing operation is missing here, and it is the pointer itself which is compared to zero. This is the correct code:Chromium project. Null pointer handling.The error was found through the V522 diagnostic: Dereferencing of the null pointer 'plugin_instance' might take place. Check the logical condition. chrome_frame_npapi chrome_frame_npapi.cc 517The condition that checks the null pointer is written incorrectly. As a result, we have a segmentation error . This is the correct code:SMTP Client with SSL/TLS project. Incomplete buffer clearing.The error was found through the V512 diagnostic: A call of the 'memset' function will lead to a buffer overflow or underflow. CSmtp md5.cpp 212For security purposes, the function tries to clear the buffer containing sensitive information. But it fails. Only the first byte will be cleared in the buffer. The error is this: the 'sizeof' operator calculates the size of the 'uint1' type instead of buffer. This is the correct code:Generally, errors of incomplete memory clearing are rather frequent. Consider some other cases like this.Chromium. Incomplete buffer clearing.The error was found through the V512 diagnostic: A call of the 'memset' function will lead to underflow of the buffer '(exploded)'. base time_win.cc 227The ZeroMemory function clears only part of the Exploded structure. The reason is that the 'sizeof' operator returns the pointer size. To fix the error, we must dereference the pointer:Apache HTTP Server project. Incomplete buffer clearing.The error was found through the V512 diagnostic: A call of the 'memset' function will lead to underflow of the buffer '(context)'. apr sha2.c 560The error is completely identical to the previous one. The 'sizeof' operator calculates the pointer size. To fix it, we must write: "sizeof(*context)".Miranda IM project. Incorrect string handling.The error was found through the diagnostics: V528 It is odd that pointer to 'char' type is compared with the '\0' value. Probably meant: *str != '\0'. clist_modern modern_skinbutton.cpp 282V528 It is odd that pointer to 'char' type is compared with the '\0' value. Probably meant: *endstr != '\0'. clist_modern modern_skinbutton.cpp 283This code is rather dangerous because it incorrectly determines the string end. It may cause a string overflow and, as a consequence, an Access Violation exception. The error lies here: "str!='\0'" and here: "endstr!='\0'". A pointer dereferencing operation is missing. This is the correct code:PNG library project. Accidental pointer clearing.The error was found through the V527 diagnostic: It is odd that the '\0' value is assigned to 'char' type pointer. Probably meant: *new_key [79] = '\0'. graphics3D pngwutil.c 1283This sample demonstrates a mistake when the programmer accidentally clears the pointer instead of truncating the string length. The point is that 'new_key' is a pointer to a string. And it means that we should write our code as follows to truncate it to 79 characters:Intel AMT SDK project. Unverified user name.The error was found through the V501 diagnostic: There are identical sub-expressions 'options->delivery_password' to the left and to the right of the '||' operator. OpenWsmanLib wsman-client.c 631Because of the developer's inattention, presence of password is checked twice, while presence of user name is not checked at all. This is the correct code:Ultimate TCP/IP project. Incorrect handling of empty strings.The error was found through the V547 diagnostic: Expression '(len - indx) >= 0' is always true. Unsigned type value is always >= 0. UTDns utstrlst.cpp 58The "len - indx" expression has the unsigned type 'size_t' and is always >= 0. Let's look what it will result in, if we send an empty string to the input.If the string is empty, then: len = 0, indx = 1.The len - indx expression is equal to 0xFFFFFFFFu.Since 0xFFFFFFFFu > 0 and indx <= 2, an array access is performed"buf[len - indx]".The "buf[0xFFFFFFFFu]" operation will cause Access Violation.Miranda IM project. Underflow protection does not work.The error was found through the V547 diagnostic: Expression 'nOldLength < 0' is always false. Unsigned type value is never < 0. IRC mstring.h 229The check "if (nOldLength < 0)" does not work since the nOldLength variable has the unsigned type.Apache HTTP Server project. Incorrect handling of negative values.The error was found through the V547 diagnostic: Expression 'len < 0' is always false. Unsigned type value is never < 0. aprutil apr_memcache.c 814The check "if (len < 0)" does not work because the 'len' variable has the unsigned type.Ultimate TCP/IP project. Incorrect condition of loop termination.The error was found through the V547 diagnostic: Expression 'loop >= 0' is always true. Unsigned type value is always >= 0. UTDns utstrlst.cpp 430Suppose the whole string consists only of spaces. While searching the characters, the program will reach the null item of the string, and the 'loop' variable will equal to zero. Then it will be decremented once again. Since this variable is of unsigned type, its value will be 0xFFFFFFFFu or 0xFFFFFFFFFFFFFFFFu (depending on the architecture). This value is 'naturally >= 0', and a new loop iteration will start. There will be an attempt of memory access by szString[0xFFFFFFFFu] address - the consequences of this are familiar to every C/C++ programmer.Crypto++ project. Private data clearing error.The error has been found with rule V597 : The compiler could delete the 'memset' function call, which is used to flush 'kappa' buffer. The RtlSecureZeroMemory() function should be used to erase the private data. cryptlib cast.cpp 293The problem is in the memset() function. The arguments passed into the function are correct. If a programmer looks how the Debug-version of this code works in the debugger, he/she won't notice the trouble either. The error occurs in the Release version of the project. The data that should have been cleared will remain in memory. The reason is that the compiler has the right to delete the call of the memset() function during optimization, and this is what it does. If you want know why it happens, read the article " Overwriting memory - why? ".Developers should not also underestimate Copy-Paste errors as well as common misprints. They are very-very numerous. Programmers spend much time on debugging them.Of course, misprints and Copy-Paste errors are similar, but there is a difference between them that caused us to place them into different groups in this article. Misprints often result in using a wrong variable instead of the needed one. And in the case of copy-paste, programmers simply forget to edit copied and pasted lines.Fennec Media Project project. Mistake while handling array items.The error was found through the V525 diagnostic: The code containing the collection of similar blocks. Check items '11', '12', '13', '13' in lines 716, 717, 718, 719. id3 editor.c 716The four similar lines must have appeared in the code through the copy-paste method. When the programmer started editing the indexes, he/she made a mistake that causes zero to be written into 'fhead[13] ' twice and not be written into 'fhead[14] '.MySQL project. Mistake while handling array items.The error was found through the V525 diagnostic: The code containing the collection of similar blocks. Check items '0', '1', '2', '3', '4', '1', '6' in lines 680, 682, 684, 689, 691, 693, 695. sql records.cc 680It is not apparent at first sight, so let's single it out:Actually there must be the following code:TortoiseSVN project. File name not corrected.The error was found through the V524 diagnostic: It is odd that the 'GetDbgHelpVersion' function is fully equivalent to the 'GetImageHlpVersion' function (SymbolEngine.h, line 98). symbolengine.h 105The 'GetImageHlpVersion' function must have appeared through copying and pasting the 'GetInMemoryFileVersion' function. The error is this: the programmer forgot to fix the file name in the copied and pasted function. This is the correct code:Clang project. Identical function bodies.The error was found through the V524 diagnostic: It is odd that the body of 'clearTopDownPointers' function is fully equivalent to the body of 'clearBottomUpPointers' function (ObjCARC.cpp, line 1318). LLVMScalarOpts objcarc.cpp 1322The body of the clearBottomUpPointers function seems to be incorrect; this function should be written as follows:QT. Unsuccessful swap.The error was found through the V519 diagnostic: The 'x1' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 2218, 2219. Qt3Support q3canvas.cpp 2219The first line is absolutely correct and swaps values in the x1 and x2 variables. In the second line, variables y1 and y2 must be swapped. This line is probably a copy of the previous one. All the 'x' letters must be replaced with letters 'y'. Unfortunately, the programmer forgot to do that in one place: "... x1=y2; ...".Correct code:Crystal Space 3D SDK project. Identical subexpressions.The error was found through the V501 diagnostic: There are identical sub-expressions to the left and to the right of the '&&' operator. plgcsopcode icelss.h 69The error is this: the 'lss.mP0.' variable is used twice here. There must be 'lss.mP1' in the first part of the expression.Notepad++ project. Setting an incorrect style.The error was found through the V525 diagnostic: The code containing the collection of similar blocks. Check items '7', '7', '6', '7' in lines 576, 580, 584, 588It is almost unreal to find this error by sight, so let's abridge the text to single out the most interesting fragments:By mistake, IDC_KEYWORD3_BOLD_CHECK is used instead of IDC_KEYWORD3_ITALIC_CHECK.ReactOS object. Choosing a wrong object.The error was found through the V523 diagnostic: The 'then' statement is equivalent to the 'else' statement. cardlib cardbutton.cpp 83The 'hsh' object is not used, while 'hhi' is used twice. This is the correct code:IPP Samples project. Incorrect check.The error was found through the V501 diagnostic: There are identical sub-expressions 'm_pContext->m_seqLayerHeader->heightMB' to the left and to the right of the '&&' operator. vc1_dec umc_vc1_video_decoder.cpp 1347Correct code:ReactOS project. Mistake in a variable name.The error was found through the V537 diagnostic: Consider reviewing the correctness of 'x' item's usage. win32k bitblt.c 670This is a very good example where you can see that a line was copied and pasted. After that, the programmer fixed the first name 'x' but forgot to fix the second. This is the correct code:C/C++ programmers have to check numerous pointers all the time to make sure that they are not equal to zero. Since these checks are numerous, the chance to make a mistake is also big. It often happens that a pointer is used first and only then is compared to NULL. Errors of this type reveal themselves very rarely. Usually the program works correctly in the standard mode and fails only in case of a non-standard situation. Instead of correctly processing a null pointer in normal mode, an Access Violation will occur and an exception will be thrown.Quake-III-Arena project. Late check.The error has been found with rule V595 : The 'item' pointer was utilized before it was verified against nullptr. Check lines: 3865, 3869. cgame ui_shared.c 3865The 'item' pointer is used first and only then is compared to NULL.LAME Ain't an MP3 Encoder project. Late check.The error has been found with rule V595 : The 'buf' pointer was utilized before it was verified against nullptr. Check lines: 226, 227. mpglib interface.c 226If 'buf' equals NULL, an exception will be thrown instead of returning the error code. And if exceptions are not used, the program will crash.daoParanoia library project. Late check.The error has been found with rule V595 : The 'v' pointer was utilized before it was verified against nullptr. Check lines: 532, 535. daoParanoia paranoia.c 532The situation here is identical to the previous ones.TrinityCore project. Late check.As you can see from the "player && ..." condition, the 'player' pointer can be equal to zero. However, this check, like in all the previous examples, is too late.We could cite many examples of such errors, but they are all alike. If you have seen a couple of such errors, be sure you've seen them all.Image Processing SDK project. Octal number.The error was found through the V536 diagnostic: Be advised that the utilized constant value is represented by an octal form. Oct: 0713, Dec: 459. IFF plugins pixelservices.inl 146If you examine the second function, you will see that the programmer intended to use number 713, not 0713. Number 0713 is declared in the octal numeral system. You can easily forget about it if you seldom use octal constants.IPP Samples project. One variable for two loops.The error was found through the V535 diagnostic: The variable 'c' is being used for this loop and for the outer loop. jpegcodec jpegdec.cpp 4652One and the same variable is used for the outer loop and the inner loop. As a result, this code will handle only part of the data or cause an eternal loop.Quake-III-Arena project. Missing return.The error has been found with rule V591 : Non-void function should return a value. botlib q_shared.h 155This code is written in C. It means that the compiler doesn't require that return should be necessarily present. But it is really necessary here. However, the code can work well due to sheer luck. Everything depends on what the EAX register contains. But it's just luck and nothing more. The function body should have been written this way: { return LongSwap(l); }.Notepad++ project. Odd condition.The error has been found with rule V590 : Consider inspecting this expression. The expression is excessive or contains a misprint. Notepad++ notepad_plus.cpp 853Perhaps this error is just a misprint, but it also could have appeared during factoring. However, it is obvious. The condition can be simplified: if (langT == L_PHP). It means that the code must have looked this way: