0% found this document useful (0 votes)
36K views62 pages

Webcache Google User Content Com Search Sclient Psy Ab HL en B

This is a snapshot of the page as it appeared on Nov 2, 2011 14:20:00 GMT. The materials collected in this article will be useful for authors of articles, books and blogs. Examples of errors can be used to demonstrate advantages of different programming styles.

Uploaded by

bobwqeqweq
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36K views62 pages

Webcache Google User Content Com Search Sclient Psy Ab HL en B

This is a snapshot of the page as it appeared on Nov 2, 2011 14:20:00 GMT. The materials collected in this article will be useful for authors of articles, books and blogs. Examples of errors can be used to demonstrate advantages of different programming styles.

Uploaded by

bobwqeqweq
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

ThisisGoogle'scacheofhttp://www.codeproject.com/KB/cpp/errors-in-open-source.aspx.ItisasnapshotofthepageasitappearedonNov2,201114:20:00 GMT.Thecurrentpagecouldhavechangedinthemeantime.

Learnmore
8,215,539 members and growing! (46,386 online) Email Password Sign in Join

Text-onlyversion
Rememberme?Lostpassword?

Home

Articles

Quick Answers

Discussions

Learning Zones

Features

Help!

TheLounge

Search

LanguagesC /C ++LanguageGeneral

90 errors in open-source projects


ByKarpov Andrey, Evgeniy Ryzhkov|1Nov2011|Unedited contribution
C ++ C Dev QA Beginner Intermediate

Licence C POL FirstPosted 1 Nov 2011 Views 9,661 Bookmarked 12 times

See Also
Morelikethis Morebythisauthor

Thematerialscollectedinthisarticlewillbeusefulforauthorsofarticles,booksandblogs.
Article Browse Code Stats Revisions
5.00(12votes)

Sponsored Links
Framewave Framewave,anopensourceAPL derivative,isacollectionof popular... developer.amd.com SSEPlus TheSSEPluslibrarysimplifiesSIMD developmentthroughoptimized... developer.amd.com Framewave Framewave,anopensourceAPL derivative,isacollectionof popular...

Abstract
Thereareactually91errorsdescribedinthearticle,butnumber90looksnicerinthetitle.Thearticleis intendedforC/C++programmers,butdevelopersworkingwithotherlanguagesmayalsofindit interesting. Thematerialscollectedinthisarticlewillbeusefulforauthorsofarticles,booksandblogs.Examplesof errorscanbeusedtodemonstrateadvantagesofdifferentprogrammingstylesforinstance,whyyou shouldnottrytomakeyourcodeshorterbywritinglongexpressions.

Examples of errors detected in various open-source projects


open in browser PRO version
Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Weregularlycheckknownandlittleknownopensourceprojects.Wedoitwiththepurposetogetan opportunitytowriteacorrespondingadvertisementitemandtestthePVSStudioanalyzeronnewcode. Manyreadersaskifwetellprojects'authorsabouterrors.Surely.Andsometimesithappensthatweget anewcustomerafterthat. Alltheexamplesofdetectederrorsaredividedintoseveralgroups.This division is rather relative. One andthesameerrorcanbereferredtomisprints,vulnerabilitiesandincorrectarrayhandlingatatime. That'swhywehavearrangedtheerrorsindifferentcategoriesjusttoshowyouthattheanalyzercan detectawiderangeofvariousdefects. Wetookonlyafewerrorsfromeachoftheprojectswehavechecked,ofcourse.Ifwedescribeallthe detectedissues,thearticlewillturnintoareferencebook.Hereisalistofprojectswehaveanalyzed: ApacheHTTPServerhttp://httpd.apache.org/ Audacityhttp://audacity.sourceforge.net/ Chromiumhttp://www.chromium.org/ Clanghttp://clanganalyzer.llvm.org/ CMakehttp://www.cmake.org/ CrystalSpace3DSDKhttp://www.crystalspace3d.org/main/Main_Page Emulehttp://www.emule.com/ FARManagerhttp://www.farmanager.com/ FCEUltrahttp://fceux.com/web/home.html FennecMediaProjecthttp://fennec.sourceforge.net/ G3DContentPakhttp://sourceforge.net/projects/g3dcpp/ IPPSampleshttp://www.viva64.com/go.php?url=449 Lugaruhttp://www.wolfire.com/lugaru MirandaIMhttp://www.mirandaim.org/ MySQLhttp://www.mysql.com/ GameDynamicshttp://newtondynamics.com/forum/newton.php Notepad++http://notepadplusplus.org/ Pixiehttp://www.renderpixie.com/ PNGlibraryhttp://libpng.org/pub/png/ QThttp://qt.nokia.com/products/ ReactOShttp://www.reactos.org/en/ Shareazahttp://www.shareaza.com/ SMTPClientwithSSL/TLShttp://www.codeproject.com/KB/IP/smtp_ssl.aspx StrongDC++http://strongdc.sourceforge.net/index.php?lang=eng SwissArmyKnifeofTracehttp://www.codeproject.com/KB/trace/tracetool.aspx TortoiseSVNhttp://tortoisesvn.net/

developer.amd.com SSEPlus TheSSEPluslibrarysimplifiesSIMD developmentthroughoptimized... developer.amd.com

See Also...
HowGoogleMapWorks ArduinoUnleashed ProfessionalSystemLibrary: Introduction frhedfreehexeditor AC oderInterviewWithDaniel Vaughan ImprovedDialogDataValidation forDoubles A3DPlottingLibraryinC # UsingC allbackBackendswiththe PantheiosLoggingAPILibrary Howtotestthereachabilityofa VPNC onnection? C asesWhenaStaticC odeAnalyzer mayHelpYou XC rashReport:ExceptionHandling andC rashReportingPart1 Aflexiblechartinglibraryfor.NET FadingBanner XC rashReport:ExceptionHandling andC rashReportingPart2 AnOracleQueryTool(part1)

The Daily Insider


30freeprogrammingbooks DailyNews:Signupnow.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

UltimateTCP/IPhttp://www.codeproject.com/KB/MFC/UltimateTCPIP.aspx VirtualDubhttp://www.virtualdub.org/ WinDjViewhttp://windjview.sourceforge.net/ WinMergehttp://winmerge.org/ Wolfenstein3Dhttp://en.wikipedia.org/wiki/Wolfenstein_3D Andsomeothers.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Figure1.Logosofprojectswehavechecked

Errors of array and string handling


ErrorsofarrayandstringhandlingarethelargestclassofdefectsinC/C++programs.Thisistheprice forthecapabilityofeffectivelowlevelmemoryhandlingavailabletoprogrammers.Inthearticlewewill showjustasmallpartoftheseerrorsfoundbythePVSStudioanalyzer.ButwethinkanyC/C++ programmerunderstandshownumerousandinsidioustheyare. Example 1.Wolfenstein3Dproject.Onlypartofanobjectiscleared.
C ollapse|C opyC ode

voidCG_RegisterItemVisuals(intitemNum){ ... itemInfo_t*itemInfo ... memset(itemInfo,0,sizeof(&itemInfo)) ... }

TheerrorwasfoundthroughtheV568diagnostic:It'soddthattheargumentofsizeof()operatoristhe '&itemInfo'expression.cgamecg_weapons.c1467. Thesizeof()operatorcalculatesthesizeofthepointerinsteadofthe'itemInfo_t'structure'ssize.Itis "sizeof(*itemInfo)"thatmustbewritten. Example 2.Wolfenstein3Dproject.Onlypartofamatrixiscleared.


C ollapse|C opyC ode

ID_INLINEmat3_t::mat3_t(floatsrc[3][3]){ memcpy(mat,src,sizeof(src)) }

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

TheerrorwasfoundthroughtheV511:Thesizeof()operatorreturnssizeofthepointer,andnotofthe array,in'sizeof(src)'expression.Splinesmath_matrix.h94 Usuallyprogrammersexpect'sizeof(src)'toreturnthesizeofanarrayequalto"3*3*sizeof(float)"bytes. Butaccordingtothelanguagestandard,'src'isjustapointer,notanarray.Thus,thematrixwillbe copiedonlypartly.The'memcpy'functionwillcopy4or8bytes(thepointersize)dependingonwhether thecodeis32bitor64bit. Ifyouwantthewholematrixtobecopied,youmaypassareferencetothearrayintothefunction.This isthecorrectcode:


C ollapse|C opyC ode

ID_INLINEmat3_t::mat3_t(float(&src)[3][3]) { memcpy(mat,src,sizeof(src)) }

Example 3.FARManagerproject.Onlypartofanarrayiscleared.
C ollapse|C opyC ode

structTreeItem { int*Last size_tLastCount ... voidClear() { strName.Clear() memset(Last,0,sizeof(Last)) Depth=0 } }

TheerrorwasfoundthroughtheV579:diagnosticThememsetfunctionreceivesthepointeranditssize asarguments.Itisprobablyamistake.Inspectthethirdargument.fartreelist.hpp66 Mostlikely,thereisamissingoperationofmultiplicationbythenumberofitemsbeingcleared,andthe codemustlookasfollows:"memset(Last,0,LastCount*sizeof(Last))". Example 4.ReactOSproject.Incorrectcalculationofastringlength.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

C ollapse|C opyC ode

staticconstPCHARNv11Board="NV11(GeForce2)Board" staticconstPCHARNv11Chip="ChipRevB2" staticconstPCHARNv11Vendor="NVidiaCorporation" BOOLEAN IsVesaBiosOk(...) { ... if(!(strncmp(Vendor,Nv11Vendor,sizeof(Nv11Vendor)))&& !(strncmp(Product,Nv11Board,sizeof(Nv11Board)))&& !(strncmp(Revision,Nv11Chip,sizeof(Nv11Chip)))&& (OemRevision==0x311)) ... }

TheerrorwasfoundthroughtheV579diagnostic:Thestrncmpfunctionreceivesthepointeranditssize asarguments.Itisprobablyamistake.Inspectthethirdargument.vgavbe.c57 Callsofthe'strncmp'functioninthiscodecompareonlythefirstseveralcharacters,notwholestrings. Theerrorhereisthis:thesizeof()operator,absolutelyinappropriateinthissituation,isusedto calculatestringlengths.Thesizeof()operatoractuallycalculatesthepointersizeinsteadofthenumber ofbytesinastring. Whatisthemostunpleasantandinsidiousaboutthiserroristhatthiscodealmostworksasintended.In 99%ofcases,comparisonofthefirstseveralcharactersisenough.Buttheremaining1%canbringyou muchfunandlongdebugging. Example 5.VirtualDubproject.Arrayoverrun(explicitindex).
C ollapse|C opyC ode

structConvoluteFilterData{ longm[9] longbias void*dyna_func DWORDdyna_size DWORDdyna_old_protect BOOLfClip } staticunsignedlong__fastcalldo_conv( unsignedlong*data, constConvoluteFilterData*cfd, longsflags,longpit)

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

{ longrt0=cfd>m[9],gt0=cfd>m[9],bt0=cfd>m[9] ... }

TheerrorwasfoundthroughtheV557diagnostic:Arrayoverrunispossible.The'9'indexispointing beyondarraybound.VirtualDubf_convolute.cpp73 Thisisoneofthesimplesterrorscausinganarrayoverrun.Index9isusedexplicitly,thoughthelast item'sindexis8.Theauthorprobablyforgot,whilewritingthiscode,thatarrayitemsinC/C++are numberedstartingwithzero,notone.Ithappenswhenyouhavetoswitchbetweendifferent programminglanguages. Example 6.CPUIdentifyingToolproject.Arrayoverrun(indexinamacro).


C ollapse|C opyC ode

#defineFINDBUFFLEN64//Maxbufferfind/replacesize ... intWINAPISticky(...) { ... staticcharfindWhat[FINDBUFFLEN]={'\0'} ... findWhat[FINDBUFFLEN]='\0' ... }

TheerrorwasfoundthroughtheV557diagnostic:Arrayoverrunispossible.The'64'indexispointing beyondarraybound.stickiesstickies.cpp7947 Thiserrorisakindofthepreviousone.Theterminalnulliswrittenoutsidethearray.Thecorrectcode is:"findWhat[FINDBUFFLEN1]='\0'". Example 7.Wolfenstein3Dproject.Arrayoverrun(incorrectexpression).


C ollapse|C opyC ode

voidBotTeamAI(bot_state_t*bs){ ... bs>teamleader[sizeof(bs>teamleader)]='\0' ... }

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

TheerrorwasfoundthroughtheV557diagnostic:Arrayoverrunispossible.The'sizeof(bs >teamleader)'indexispointingbeyondarraybound.gameai_team.c548 Hereisonemoreexampleofanarrayoverrunwhenusinganexplicitlydeclaredindex.Thesesamples showthatsuchsimpleatfirstsighterrorsaremuchmorewidelyspreadthanitmayseem. Theterminalnulliswrittenoutsidethe'teamleader'array.Thisisthecorrectcode:


C ollapse|C opyC ode

bs>teamleader[sizeof(bs>teamleader)1]='\0'

Example 8.MirandaIMproject.Onlypartofastringiscopied.
C ollapse|C opyC ode

typedefstruct_textrangew { CHARRANGEchrg LPWSTRlpstrText }TEXTRANGEW constwchar_t*Utils::extractURLFromRichEdit(...) { ... ::CopyMemory(tr.lpstrText,L"mailto:",7) ... }

TheerrorwasfoundthroughtheV512diagnostic:Acallofthe'memcpy'functionwillleadtoabuffer overfloworunderflow.tabsrmmutils.cpp1080 IfUnicodestringsareused,onecharacteroccupies2or4bytes(dependingonthedatamodelbeing usedincompiler)insteadofonebyte.Unfortunately,programmerseasilyforgetaboutit,andyoucan oftenseedefectslikeourexampleinprograms. The'CopyMemory'functionwillcopyonlypartoftheL"mailto:"stringsinceithandlesbytes,not characters.Youcanfixthecodebyusingamoreappropriatefunctionforstringcopyingor,atleast, multiplyingnumber7bysizeof(wchar_t). Example 9.CMakeproject.Arrayoverruninsidealoop.
C ollapse|C opyC ode

staticconststruct{

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

DWORDwinerr intdoserr }doserrors[]= { ... } staticvoid la_dosmaperr(unsignedlonge) { ... for(i=0i<sizeof(doserrors)i++) { if(doserrors[i].winerr==e) { errno=doserrors[i].doserr return } } ... }

TheerrorwasfoundthroughtheV557diagnostic:Arrayoverrunispossible.Thevalueof'i'indexcould reach367.cmlibarchivearchive_windows.c1140,1142 Theerrorhandleritselfcontainsanerror.Thesizeof()operatorreturnsthearraysizeinbytesandnot thenumberofitemsinsideit.Asaresult,theprogramwilltrytosearchmuchmoreitemsthanitshould intheloop.Thisisthecorrectloop:


C ollapse|C opyC ode

for(i=0i<sizeof(doserrors)/sizeof(*doserrors)i++)

Example 10.CPUIdentifyingToolproject.Astringisprintedintoitself.
C ollapse|C opyC ode

char*OSDetection() { ... sprintf(szOperatingSystem, "%sversion%d.%d%s(Build%d)", szOperatingSystem, osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.szCSDVersion,

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

osvi.dwBuildNumber&0xFFFF) ... sprintf(szOperatingSystem,"%s%s(Build%d)", szOperatingSystem,osvi.szCSDVersion, osvi.dwBuildNumber&0xFFFF) ... }

ThiserrorwasfoundthroughtheV541diagnostic:Itisdangeroustoprintthestring'szOperatingSystem' intoitself.stickiescamel.cpp572,603 Anattemptofformattedprintingofastringintoitselfcanleadtobadconsequences.Theresultof executingthiscodedependsontheinputdata,andyoucannotpredictwhatwillhappen.Mostlikely, theresultwillbeameaninglessstringoranAccessViolationwilloccur. Thiserrorcanbereferredtothecategory"codevulnerabilities".Insomeprograms,byfeedingspecial datatocode,youcanexploitsuchcodefragmentstocauseabufferoverfloworothereffectsan intruderneeds. Example 11.FCEUltraproject.Astringgetslessmemorythanneeded.
C ollapse|C opyC ode

intFCEUI_SetCheat(...) { ... if((t=(char*)realloc(next>name,strlen(name+1)))) ... }

TheerrorwasfoundthroughtheV518diagnostic:The'realloc'functionallocatesstrangeamountof memorycalculatedby'strlen(expr)'.Perhapsthecorrectvariantis'strlen(expr)+1'.fceuxcheat.cpp 609 Thiserroriscausedbyamisprint.Itisthe'name'pointerinsteadofthe"name+1"expressionthatmust betheargumentofthestrlen()function.Asaresult,thereallocfunctionallocates2byteslessmemory thanneeded:onebyteislostbecause1isnotaddedtothestringlengthanotherbyteislostbecause the'strlen'functioncalculatesthestringlengthskippingthefirstcharacter. Example 12.Notepad++project.Partialarrayclearing.


C ollapse|C opyC ode

#defineCONT_MAP_MAX50

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

int_iContMap[CONT_MAP_MAX] ... DockingManager::DockingManager() { ... memset(_iContMap,1,CONT_MAP_MAX) ... }

TheerrorwasfoundthroughtheV512diagnostic:Acallofthememsetfunctionwillleadtoabuffer overfloworunderflow.notepadPlusDockingManager.cpp60 That'sonemoreexampleofhowthenumberofarrayitemsismixedupwithanarraysize.A multiplicationbysizeof(int)ismissing. Wecangoonandonshowingyouerrorsofarrayhandlingwehavefoundinvariousprograms.Butwe havetostopsomewhere.Letitbe12,fornumber13isconsideredtobeunlucky.

Undefined behavior
Abitoftheoryatfirst. Undefinedbehaviorisapropertyofcertainprogramminglanguages(mostprominentinCandC++)to producearesultincertainsituationsthatdependsoncompilerimplementationorspecifiedoptimization switches.Inotherwords,thespecificationdoesnotdefinethelanguage'sbehaviorinanypossible situationsbutsays:"atAcondition,theresultofBoperationisundefined".Itisconsideredamistaketo allowsuchasituationinyourprogramevenifitisexecutedwellatsomeparticularcompiler.Sucha programwillnotbecrossplatformandmaycausefailuresonadifferentcomputer,operatingsystemand evenatdifferentcompiler'ssettings. Asequencepointinprogrammingisanypointinaprogramwhereitisguaranteedthatthesideeffects ofallthepreviouscalculationshavealreadyemergedwhiletherearenosideeffectsofthefollowing calculationsyet.Tolearnmoreaboutsequencepointsandcasesofundefinedbehaviorrelatedto sequencepoints,seethispost:http://www.viva64.com/en/t/0065/. Example 1.Chromiumproject.Incorrectuseofsmartpointer.
C ollapse|C opyC ode

voidAccessibleContainsAccessible(...) { ... auto_ptr<VARIANT>child_array(newVARIANT[child_count])

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

... }

TheerrorwasfoundthroughtheV554diagnostic:Incorrectuseofauto_ptr.Thememoryallocatedwith 'new[]'willbecleanedusing'delete'.interactive_ui_testsaccessibility_win_browsertest.cc171 Thisexampledemonstratesthecasewhenusingasmartpointercancauseundefinedbehavior.Itmay beexpressedthroughheapdamage,programcrash,incompleteobjectdestructionoranyotherfailure. Theerroristhis:memoryisallocatedbythenew[]operatorandreleasedbythedeleteoperatorinthe 'auto_ptr'class'destructor:


C ollapse|C opyC ode

~auto_ptr(){ delete_Myptr }

Tofixtheseissues,youshoulduseamoreappropriateclass,forinstance,boost::scoped_array. Example 2.IPPSamplesproject.ClassicUndefinedbehavior.


C ollapse|C opyC ode

template<typenameT,Ipp32ssize>voidHadamardFwdFast(...) { Ipp32s*pTemp ... for(j=0j<4j++){ a[0]=pTemp[0*4]+pTemp[1*4] a[1]=pTemp[0*4]pTemp[1*4] a[2]=pTemp[2*4]+pTemp[3*4] a[3]=pTemp[2*4]pTemp[3*4] pTemp=pTemp++ ... } ... }

TheerrorwasfoundthroughtheV567diagnostic:Undefinedbehavior.The'pTemp'variableismodified whilebeingusedtwicebetweensequencepoints.meumc_me_cost_func.h168 Thisisaclassicexampleofundefinedprogrambehavior.Itisthisconstructwhichisusedto demonstrateUndefinedbehaviorinvariousarticles.Itisunknownwhether'pTemp'willbeincrementedby oneornot.TwoactionsofchangingpTempvariable'svaluearelocatedinonesequencepoint.Itmeans

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

thatthecompilermaycreatethefollowingcode: pTemp=pTemp+1 pTemp=pTemp Oritmaycreateanotherversionofthecode: TMP=pTemp pTemp=pTemp+1 pTemp=TMP Whichofthetwocodeversionswillbecreateddependsonthecompilerandoptimizationswitches. Example 3.FennecMediaProjectproject.Complexexpression.
C ollapse|C opyC ode

uint32CUnBitArrayOld::DecodeValueRiceUnsigned(uint32k) { ... while(!(m_pBitArray[m_nCurrentBitIndex>>5]& Powers_of_Two_Reversed[m_nCurrentBitIndex++&31])){} ... }

TheerrorwasfoundthroughtheV567diagnostic:Undefinedbehavior.The'm_nCurrentBitIndex'variable ismodifiedwhilebeingusedtwiceatsinglesequencepoint.MACLibunbitarrayold.cpp78 Therearenosequencepointsbetweentwoinstancesofusingthe'm_nCurrentBitIndex'variable.It meansthatthestandarddoesnotspecifythemomentwhenthisvariableisincremented. Correspondingly,thiscodemayworkdifferentlydependingonthecompilerandoptimizationswitches. Example 4.MirandaIMproject.Complexexpression.


C ollapse|C opyC ode

shortezxml_internal_dtd(ezxml_root_troot, char*s,size_tlen) { ... while(*(n=++s+strspn(s,EZXML_WS))&&*n!='>'){ ...

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

TheerrorwasfoundthroughtheV567diagnostic:Undefinedbehavior.The's'variableismodifiedwhile beingusedtwicebetweensequencepoints.msnezxml.c371 Prefixincrementofthevariableisusedhere.Butitdoesnotmeananything:itcannotbeguaranteed thatthe's'variablewillbeincrementedbeforecallingthestrspn()function.

Errors relating to operation priorities.


Tomakeunderstandingofexampleseasier,let'srecalltheoperationprioritiestable.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Figure2OperationprioritiesinC/C++ Example 1.MySQLproject.Prioritiesof!and&operations.


C ollapse|C opyC ode

intha_innobase::create(...) { ... if(srv_file_per_table &&!mysqld_embedded &&(!create_info>options&HA_LEX_CREATE_TMP_TABLE)){ ... }

TheerrorwasfoundthroughtheV564diagnostic:The'&'operatorisappliedtobooltypevalue.You've probablyforgottentoincludeparenthesesorintendedtousethe'&&'operator.innobaseha_innodb.cc 6789 Theprogrammerwantedapartoftheexpressiontocheckthatacertainbitinthe'create_info>options' variableisequaltozero.Butthepriorityofthe'!'operationishigherthanthatofthe'&'operation, that'swhytheexpressionworksbythisalgorithm:


C ollapse|C opyC ode

((!create_info>options)&HA_LEX_CREATE_TMP_TABLE) Weshoulduseadditionalparenthesesifwewantthecodetoworkproperly:

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

(!(create_info>options&HA_LEX_CREATE_TMP_TABLE))

Or,whatwefindnicer,writethecodeinthefollowingway:
C ollapse|C opyC ode

((create_info>options&HA_LEX_CREATE_TMP_TABLE)==0)

Example 2.Emuleproject.Prioritiesof*and++operations.
C ollapse|C opyC ode

STDMETHODIMP CCustomAutoComplete::Next(...,ULONG*pceltFetched) { ... if(pceltFetched!=NULL) *pceltFetched++ ... }

TheerrorwasfoundthroughtheV532diagnostic:Considerinspectingthestatementof'*pointer++' pattern.Probablymeant:'(*pointer)++'.emulecustomautocomplete.cpp277 If'pceltFetched'isnotanullpointer,thefunctionmustincrementthevariableoftheULONGtypethis pointerrefersto.Theerroristhis:thepriorityofthe'++'operationishigherthanthatof'*'operation (pointerdereferencing).The"*pceltFetched++"lineisidenticaltothefollowingcode:


C ollapse|C opyC ode

TMP=pceltFetched+1 *pceltFetched pceltFetched=TMP

Virtuallyitisjustincrementofthepointer.Tomakethecodecorrect,wemustaddparentheses: "(*pceltFetched)++". Example 3.Chromiumproject.Prioritiesof&and!=operations.


C ollapse|C opyC ode

#defineFILE_ATTRIBUTE_DIRECTORY0x00000010 boolGetPlatformFileInfo(PlatformFilefile,PlatformFileInfo*info){ ...

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

info>is_directory= file_info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY!=0 ... }

TheerrorwasfoundthroughtheV564diagnostic:The'&'operatorisappliedtobooltypevalue.You've probablyforgottentoincludeparenthesesorintendedtousethe'&&'operator.baseplatform_file_win.cc 216 Programmerseasilyforgetthatthepriorityofthe'!='operationishigherthanthatof'&'.Thisiswhat happenedinourcase.Asaresult,wehavethefollowingexpression:


C ollapse|C opyC ode

info>is_directory= file_info.dwFileAttributes&(0x00000010!=0)

Let'ssimplifytheexpression:
C ollapse|C opyC ode

info>is_directory=file_info.dwFileAttributes&(true)

Let'ssimplifyitonceagain:
C ollapse|C opyC ode

info>is_directory=file_info.dwFileAttributes&1

Itturnsoutthatwehavetestedthefirstbitinsteadofthefifthbit.Tofixthis,weneedtoadd parentheses. Example 4.BCmenuproject.IFandELSEmixedup.


C ollapse|C opyC ode

voidBCMenu::InsertSpaces(void) { if(IsLunaMenuStyle()) if(!xp_space_accelerators)return else if(!original_space_accelerators)return ... }

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

TheerrorwasfoundthroughtheV563diagnostic:Itispossiblethatthis'else'branchmustapplytothe previous'if'statement.firebcmenu.cpp1853 Thisisnotanerrorofoperationpriorities,butonerelativetoit.Theprogrammerdoesnottakeinto accountthatthe'else'branchreferstothenearest'if'operator.Wecanseethatthecodejustification asifitworksbythefollowingalgorithm:


C ollapse|C opyC ode

if(IsLunaMenuStyle()){ if(!xp_space_accelerators)return }else{ if(!original_space_accelerators)return }

Butactuallyitisequivalenttothefollowingconstruct:
C ollapse|C opyC ode

if(IsLunaMenuStyle()) { if(!xp_space_accelerators){ return }else{ if(!original_space_accelerators)return } }

Example 5.IPPSamplesproject.Prioritiesof?:and|operations.
C ollapse|C opyC ode

vm_file*vm_file_fopen(...) { ... mds[3]=FILE_ATTRIBUTE_NORMAL| (islog==0)?0:FILE_FLAG_NO_BUFFERING ... }

TheerrorwasfoundthroughtheV502diagnostic:Perhapsthe'?:'operatorworksinadifferentwaythan itwasexpected.The'?:'operatorhasalowerprioritythanthe'|'operator.vmvm_file_win.c393 Dependingonthe'islog'variable'svalue,theexpressionmustbeeitherequalto "FILE_ATTRIBUTE_NORMAL"or"FILE_ATTRIBUTE_NORMAL|FILE_FLAG_NO_BUFFERING".Butitdoesnot

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

happen.Priorityofthe'?:'operationislowerthanthatof'|'.Asaresult,thecodeactsasfollows:
C ollapse|C opyC ode

mds[3]=(FILE_ATTRIBUTE_NORMAL|(islog==0))? 0:FILE_FLAG_NO_BUFFERING

Let'ssimplifytheexpression:
C ollapse|C opyC ode

mds[3]=(0x00000080|...)?0:FILE_FLAG_NO_BUFFERING

SinceFILE_ATTRIBUTE_NORMALequals0x00000080,theconditionisalwaystrue.Itmeansthat0will alwaysbewrittenintomds[3]. Example 6.NewtonGameDynamicsproject.Prioritiesof?:and*operations.


C ollapse|C opyC ode

dgInt32CalculateConvexShapeIntersection(...) { ... den=dgFloat32(1.0e24f)* (den>dgFloat32(0.0f))? dgFloat32(1.0f):dgFloat32(1.0f) ... }

TheerrorwasfoundthroughtheV502diagnostic:Perhapsthe'?:'operatorworksinadifferentwaythan itwasexpected.The'?:'operatorhasalowerprioritythanthe'*'operator.physics dgminkowskiconv.cpp1061 Theerrorinthiscodeagainrelatestothelowpriorityofthe'?:'operation.Theconditionforthe'?:' operatorisexpressedbyameaninglesssubexpression"dgFloat32(1.0e24f)*(den>dgFloat32(0.0f))". Addingparentheseswillsolvetheissue. Bytheway,programmersoftenforgethowcunningthe'?:'operatoris.Hereisapostonthistopic: "Howtomakefewererrorsatthestageofcodewriting.PartN2".

Formatted output errors


Examplesoftheseerrorsareboringandalike,sowewillexamineonlyafewsamples.Thepointisthat functionswithavariablenumberofargumentsacceptactualargumentsincompatiblewiththeformat

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

string.Anyprogrammerwhousessuchfunctionsasprintf()isfamiliarwiththistypeoferrors. Example 1.ReactOSproject.IncorrectprintingofaWCHARcharacter.


C ollapse|C opyC ode

staticvoidREGPROC_unescape_string(WCHAR*str) { ... default: fprintf(stderr, "Warning!Unrecognizedescapesequence:\\%c'\n", str[str_idx]) ... }

TheerrorwasfoundthroughtheV576diagnostic:Incorrectformat.Considercheckingthethirdactual argumentofthe'fprintf'function.Thechartypeargumentisexpected.regeditregproc.c293 Thefprinf()functionmustprintacharacterofthechartype.Butthethirdargumentisacharacterof theWCHARtype.Theuserwillgetanincorrectlygeneratedmessage.Tofixthecode,weshouldreplace '%c'with'%C'intheformatstring. Example 2.IntelAMTSDKproject.Character'%'missing.


C ollapse|C opyC ode

voidaddAttribute(...) { ... intindex=_snprintf(temp,1023, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:" "%02x%02x:02x%02x:%02x%02x:%02x%02x", value[0],value[1],value[2],value[3],value[4], value[5],value[6],value[7],value[8], value[9],value[10],value[11],value[12], value[13],value[14],value[15]) ... }

TheerrorwasfoundthroughtheV576diagnostic:Incorrectformat.Adifferentnumberofactual argumentsisexpectedwhilecalling'_snprintf'function.Expected:18.Present:19.mod_pvs mod_pvs.cpp308 Itisnoteasytofindanerrorhereatfirstsight.However,thePVSStudioanalyzerdoesnotgettired

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

andnoticesthatthefunctiontakesmoreactualargumentsthanspecifiedintheformatstring.The reasonisthatthe'%'characterismissinginoneplace.Let'ssingleoutthisfragment:
C ollapse|C opyC ode

"%02x%02x:[HERE]02x%02x:%02x%02x:%02x%02x",

Example 3.IntelAMTSDKproject.Unusedargument.
C ollapse|C opyC ode

boolGetUserValues(...) { ... printf("Error:illegalvalue.Aborting.\n",tmp) returnfalse }

TheerrorwasfoundthroughtheV576diagnostic:Incorrectformat.Adifferentnumberofactual argumentsisexpectedwhilecalling'printf'function.Expected:1.Present:2.RemoteControlSample remotecontrolsample.cpp792 Theerroristhis:the'tmp'variableisnotusedinanywaywhenprintingtheinformationmessage. Example 4.G3DContentPakproject.Printingofmeaninglessdata.


C ollapse|C opyC ode

classMatrix3{ ... inlinefloat*operator[](intiRow){ ... } voidAnyVal::serialize(G3D::TextOutput&t)const{ ... constMatrix3&m=*(Matrix3*)m_value ... t.printf("%10.5f,%10.5f,%10.5f,\n %10.5f,%10.5f,%10.5f,\n %10.5f,%10.5f,%10.5f)", m[0,0],m[0,1],m[0,2], m[1,0],m[1,1],m[1,2], m[2,0],m[2,1],m[2,2]) ... }

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

TheerrorwasfoundthroughtheV520diagnostic:Thecommaoperator','inarrayindexexpression'[0, 0]'.graphics3Danyval.cpp275 Theprogramprintsmeaninglessvaluesinsteadofthematrix.Youmaywritesuchacodewhenyouwork withdifferentprogramminglanguagesandsometimesforgethowtoaccessaniteminatwodimensional arrayintheClanguage. Let'sseehowthe'm[0,1]'expressionworks.Atfirst,expression"0,1"iscalculated.Theresultofthis expressionis1.Thenthe'operator[]'functioniscalledintheMatrix3class.Thefunctiontakesthe actualargument1andreturnsthepointertothefirststringinthematrix.Itisthevalueofthispointer thatwillbeprintedbythe'printf()'functionthoughitexpectsavalueofthefloattype. Thisisthecorrectcode:
C ollapse|C opyC ode

t.printf("%10.5f,%10.5f,%10.5f,\n %10.5f,%10.5f,%10.5f,\n %10.5f,%10.5f,%10.5f)", m[0][0],m[0][1],m[0][2], m[1][0],m[1][1],m[1][2], m[2][0],m[2][1],m[2][2])

Examples of misprints found in code


Alotofprogrammingerrorsarecausedbymisprints.Mostoftheseerrorsarequicklydetectedatthe earlystagesoftesting.Buttherearesomedefectsofthiskindthatremainincodeforalongtime causingtroublesbothtoprogrammersandusers. YoucanmaketheseerrorsmuchfewerusingthePVSStudioanalyzer.Itwillfindthembeforetesting starts,whichwillsignificantlyreducethecostofdefectdetectionandelimination. Example 1.MirandaIMproject.AssignmentinsideIF.
C ollapse|C opyC ode

voidCIcqProto::handleUserOffline(BYTE*buf,WORDwLen) { ... elseif(wTLVType=0x29&&wTLVLen==sizeof(DWORD)) ... }

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

TheerrorwasfoundthroughtheV560diagnostic:Apartofconditionalexpressionisalwaystrue:0x29. icqoscar8fam_03buddy.cpp632 Becauseofamisprint,thereisanassignmenttakingplaceinsidetheconditionofthe'if'operator.Thisis thecorrectcondition:"if(wTLVType==0x29&&wTLVLen==sizeof(DWORD))". Example 2. ReactOSproject.Assignmenterror.


C ollapse|C opyC ode

BOOLWINAPIGetMenuItemInfoA(...) { ... mii>cch=mii>cch ... }

TheerrorwasfoundthroughtheV570diagnostic:The'mii>cch'variableisassignedtoitself.user32 menu.c4347 Thevalueofthevariableisassignedtoitself.Theprogrammerapparentlyintendedtowriteitinthis way:"mii>cch=miiW>cch". Example 3. Clangproject.Objectnamemisprinted.


C ollapse|C opyC ode

staticValue*SimplifyICmpInst(...){ ... caseInstruction::Shl:{ boolNUW= LBO>hasNoUnsignedWrap()&&LBO>hasNoUnsignedWrap() boolNSW= LBO>hasNoSignedWrap()&&RBO>hasNoSignedWrap() ... }

TheerrorwasfoundthroughtheV501diagnostic:Thereareidenticalsubexpressions'LBO >hasNoUnsignedWrap()'totheleftandtotherightofthe'&&'operator.LLVMAnalysis instructionsimplify.cpp1891 Thereisamisprintwhenusingvariableswithsimilarnames.Inthefirstline,bothLBOandRBOvariables mustbeused.Thisisthecorrectcode:

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

C ollapse|C opyC ode

boolNUW=LBO>hasNoUnsignedWrap()&&RBO>hasNoUnsignedWrap()

Example 4. Notepad++project.Incorrectstatetest.
C ollapse|C opyC ode

bool_isPointXValid bool_isPointYValid ... boolisPointValid(){ return_isPointXValid&&_isPointXValid }

TheerrorwasfoundthroughtheV501diagnostic:Thereareidenticalsubexpressionstotheleftandto therightofthe'&&'operator._isPointXValid&&_isPointXValid Thename'_isPointXValid'isusedtwice.Thefunctionmustactuallyreturnthiscode:"_isPointXValid&& _isPointYValid". Example 5. StrongDC++project.Unsuccessfulcheckof\r\n.


C ollapse|C opyC ode

staticvoidgetContentLengthAndHeaderLength(...) { ... while(line[linelen]!='\r'&&line[linelen]!='\r') ... }

TheerrorwasfoundthroughtheV501diagnostic:Thereareidenticalsubexpressions'line[linelen]!= '\r''totheleftandtotherightofthe'&&'operator.miniupnpcminiupnpc.c153 Becauseofamisprint,presenceofthe'\r'characterischeckedtwice.Actuallypresenceofthe'\n' charactermustbecheckedtoo. Example 6. G3DContentPakproject.Aclosingparenthesisinawrongplace.


C ollapse|C opyC ode

boolMatrix4::operator==(constMatrix4&other)const{ if(memcmp(this,&other,sizeof(Matrix4)==0)){ returntrue }

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

} ... }

TheerrorwasfoundthroughtheV575diagnostic:The'memcmp'functionprocesses'0'elements. Inspectthe'third'argument.graphics3Dmatrix4.cpp269 Oneclosingparenthesisisinawrongplace.Itturnsoutthatthesizeofthememoryareabeing comparediscalculatedbythe"sizeof(Matrix4)==0"expression.Thisexpressionalwayshasthe'false' result.Then'false'turnsintoanintegervalueequalto0.Thisisthecorrectcode:


C ollapse|C opyC ode

if(memcmp(this,&other,sizeof(Matrix4))==0){

Example 7. QTproject.Errorofstructuremembercopying.
C ollapse|C opyC ode

PassRefPtr<Structure> Structure::getterSetterTransition(Structure*structure) { ... transition>m_propertyStorageCapacity= structure>m_propertyStorageCapacity transition>m_hasGetterSetterProperties= transition>m_hasGetterSetterProperties transition>m_hasNonEnumerableProperties= structure>m_hasNonEnumerableProperties transition>m_specificFunctionThrashCount= structure>m_specificFunctionThrashCount ... }

TheerrorwasfoundthroughtheV570diagnostic:The'transition>m_hasGetterSetterProperties'variable isassignedtoitself.QtScriptstructure.cpp512 Itisnoteasytofindanerrorlookingatthiscode.Butitisthere.Thefield'm_hasGetterSetterProperties' iscopiedintoitself.Thisisthecorrectcode:


C ollapse|C opyC ode

transition>m_hasGetterSetterProperties= structure>m_hasGetterSetterProperties

Example 8. ApacheHTTPServerproject.Extrasizeofoperator.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

C ollapse|C opyC ode

PSECURITY_ATTRIBUTESGetNullACL(void) { PSECURITY_ATTRIBUTESsa sa=(PSECURITY_ATTRIBUTES) LocalAlloc(LPTR,sizeof(SECURITY_ATTRIBUTES)) sa>nLength=sizeof(sizeof(SECURITY_ATTRIBUTES)) ... }

TheerrorwasfoundthroughtheV568diagnostic:It'soddthattheargumentofsizeof()operatoristhe 'sizeof(SECURITY_ATTRIBUTES)'expression.libhttpdutil_win32.c115 Thefield'nLength'mustcontainthesizeofthe'SECURITY_ATTRIBUTES'structure.Thereisamisprintin thecode:the'sizeof'operatorisusedtwice.Asaresult,thefield'nLength'storesasizeofthe'size_t' type.Thisisthecorrectcode:


C ollapse|C opyC ode

sa>nLength=sizeof(SECURITY_ATTRIBUTES)

Example 9. FCEUltraproject.Doublevariabledeclaration.
C ollapse|C opyC ode

intiNesSaveAs(char*name) { ... fp=fopen(name,"wb") intx=0 if(!fp) intx=1 ... }

TheerrorwasfoundthroughtheV561diagnostic:It'sprobablybettertoassignvalueto'x'variablethan todeclareitanew.Previousdaclaration:ines.cpp,line960.fceuxines.cpp962 The'x'variablemuststoreinformationwhetherornotafilewasopenedsuccessfully.Becauseofa misprint,anewvariablenamed'x'iscreatedandinitializedinsteadofassigning1totheexistingvariable. Thisishowthecorrectcodemustlook:


C ollapse|C opyC ode

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

if(!fp) x=1

Example 10. Notepad++project.Using&&operatorinsteadof&.


C ollapse|C opyC ode

TCHARGetASCII(WPARAMwParam,LPARAMlParam) { ... result=ToAscii(wParam, (lParam>>16)&&0xff,keys,&dwReturnedValue,0) ... }

TheerrorwasfoundthroughtheV560diagnostic:Apartofconditionalexpressionisalwaystrue:0xff. notepadPlusbabygrid.cpp694 The"(lParam>>16)&&0xff"expressionismeaninglessandisalwaysequalto1(true).Amisprinthereis inusingthe'&&'operatorinsteadof'&'. Example 11. WinDjViewproject.Incompletecondition.


C ollapse|C opyC ode

inlineboolIsValidChar(intc) { returnc==0x9||0xA||c==0xD||c>=0x20&& c<=0xD7FF||c>=0xE000&&c<=0xFFFD|| c>=0x10000&&c<=0x10FFFF }

TheerrorwasfoundthroughtheV560diagnostic:Apartofconditionalexpressionisalwaystrue:0xA. WinDjViewxmlparser.cpp45False TheIsValidCharfunctionalwaysreturns'true'.Comparisonismissinginoneplacebecauseofamisprint: "...||0xA||...". Example 12. FennecMediaProjectproject.Extrasemicolon.


C ollapse|C opyC ode

intsettings_default(void) { ...

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

for(i=0i<16i++) for(j=0j<32j++) { settings.conversion.equalizer_bands.boost[i][j]=0.0 settings.conversion.equalizer_bands.preamp[i]=0.0 } }

TheerrorwasfoundthroughtheV529diagnostic:Oddsemicolon''after'for'operator.settings.c483 AlltheCandC++programmersknowhowdangerousanextrasemicolon''is.Unfortunately,this knowledgedoesnotpreventthemfrommakingsuchmisprints.Thereisanextrasemicolonafterthefirst 'for'operator,whichmakesthisprogramfragmentunabletoexecute. Example 13. QTproject.Missingbreakoperator.


C ollapse|C opyC ode

intQCleanlooksStyle::pixelMetric(...) { ... casePM_SpinBoxFrameWidth: ret=3 break casePM_MenuBarItemSpacing: ret=6 casePM_MenuBarHMargin: ret=0 break ... }

TheerrorwasfoundthroughtheV519diagnostic:The'ret'variableisassignedvaluestwice successively.Perhapsthisisamistake.Checklines:3765,3767.QtGuiqcleanlooksstyle.cpp3767 Thisisaclassicerror'break'ismissinginsidethe'switch'operator.Ithinkyoudonotneedanyfurther commentshere. Example 14. MirandaIMproject.Assignmentinsteadofcomparison.


C ollapse|C opyC ode

intFindItem(...) { ...

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

intret ret=FindItem(hwnd,dat,hItem, (structClcContact**)&z, (structClcGroup**)&isv,NULL) if(ret=0){return(0)} ... }

TheerrorwasfoundthroughtheV559diagnostic:Suspiciousassignmentinsidetheconditionexpression of'if'operator:ret=0.clist_mwclcidents.c179 Thereisamisprintinsidetheconditionofthe'if'operator:'='iswritteninsteadof'=='.Thefunctionwill handlethesituationincorrectlywhenacertainitemisnotfound. Example 15. IPPSamplesproject.Incorrectindex.


C ollapse|C opyC ode

structAVS_MB_INFO { ... Ipp8urefIdx[AVS_DIRECTIONS][4] ... } voidAVSCompressor::GetRefIndiciesBSlice(void){ ... if(m_pMbInfo>predType[0]&predType) { m_refIdx[iRefNum]=m_pMbInfo>refIdx[dir][0] iRefNum+=1 } if(m_pMbInfo>predType[1]&predType) { m_refIdx[iRefNum]=m_pMbInfo>refIdx[dir][1] iRefNum+=1 } if(m_pMbInfo>predType[2]&predType) { m_refIdx[iRefNum]=m_pMbInfo>refIdx[dir][2] iRefNum+=1 } if(m_pMbInfo>predType[3]&predType) { m_refIdx[iRefNum]=m_pMbInfo>refIdx[dir][30] iRefNum+=1

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

} ... }

TheerrorwasfoundthroughtheV557diagnostic:Arrayoverrunispossible.The'30'indexispointing beyondarraybound.avs_encumc_avs_enc_compressor_enc_b.cpp495 Considerthisfragment:"m_pMbInfo>refIdx[dir][30]".Becauseofamisprint,number30iswritten insteadofindex3.Bytheway,thissampleshowswellhowrelativeourdivisionoferrorsintocategories is.Thiserrormightwellbereferredtothecategory"Errorsofarrayandstringhandling".Thedivisionis relativeandismadetoshowdiversityoferrorsthePVSStudioanalyzercandetect. Example 16. ReactOSproject.Misprintinamacro.


C ollapse|C opyC ode

#defineSWAP(a,b,c)c=a\ a=b\ a=c

TheerrorwasfoundthroughtheV519diagnostic:The'v2'variableisassignedvaluestwice successively.Perhapsthisisamistake.Checklines:343,343.win32kgradient.c343 Itisaratherfunnymisprintinamacrointendedtoswapvaluesintwovariables.Lookcloselyatthe codeandyouwillseewhatImean.Thisisthecorrectcode:


C ollapse|C opyC ode

#defineSWAP(a,b,c)c=a\ a=b\ b=c

Thistimewedidnotmanagetostopatthe13thexample:somanyerrorsinsoftwarearecausedby misprints.Therearemuchmoreerrorsofthiskindthanprogrammersthink.Wecouldgoonandoninthis sectionbutwedecidetostopatthe16thexampleatlast.

Incorrect use of base functions and classes


Example 1. FennecMediaProject.Twoterminalnullsabsent.
C ollapse|C opyC ode

intJoiningProc(HWNDhwnd,UINTuMsg, WPARAMwParam,LPARAMlParam)

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

{ ... OPENFILENAMElofn memset(&lofn,0,sizeof(lofn)) ... lofn.lpstrFilter=uni("AllFiles(*.*)\0*.*") ... }

TheerrorwasfoundthroughtheV540diagnostic:Member'lpstrFilter'shouldpointtostringterminated bytwo0characters.basewindows.c5309 InWindowsAPItherearestructuresinwhichpointerstostringsmustendwithtwonullcharacters.Itis thatverykindofstringthe'lpstrFilter'memberintheOPENFILENAMEstructurepointsto. Descriptionof'lpstrFilter'inMSDN: LPCTSTR Abuffercontainingpairsofnullterminatedfilterstrings.Thelaststringinthebuffermustbe terminatedbytwoNULLcharacters. Ifyouforgettowriteanadditionalnullattheend,thedialogueoffilehandlingmaycontaingarbagein thefilterfields.Thisisthecorrectcode:
C ollapse|C opyC ode

lofn.lpstrFilter=uni("AllFiles(*.*)\0*.*\0")

Example 2. TortoiseSVNproject.Incorrectuseof'remove'function.
C ollapse|C opyC ode

STDMETHODIMPCShellExt::Initialize(....) { ... ignoredprops=UTF8ToWide(st.c_str()) //removeallescapechars('\\') std::remove(ignoredprops.begin(),ignoredprops.end(),'\\'); break ... }

TheerrorwasfoundthroughtheV530diagnostic:Thereturnvalueoffunction'remove'isrequiredtobe

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

utilized.contextmenu.cpp442 Thestd::removefunctiondoesnotremoveitemsfromthecontainer.Itonlyshiftstheitemsandreturns theiteratortothebeginningoftrash.Assumewehaveavector<int>containerthatcontainsitems 1,2,3,1,2,3,1,2,3.Ifweexecutethecode"remove(v.begin(),v.end(),2)",thecontainerwillcontain items1,3,1,3,X,X,X,whereXissometrash.Thefunctionwillreturntheiteratortothefirsttrashitem, soifwewanttoremovethesetrashitems,weneedtowritethecode:"v.erase(remove(v.begin(), v.end(),2),v.end())". Example 3. TortoiseSVNproject.Using'empty'functioninsteadof'clear'.


C ollapse|C opyC ode

CMailMsg&CMailMsg::SetFrom(stringsAddress, stringsName) { if(initIfNeeded()) { //onlyonesenderallowed if(m_from.size()) m_from.empty() m_from.push_back(TStrStrPair(sAddress,sName)) } return*this }

TheerrorwasfoundthroughtheV530diagnostic:Thereturnvalueoffunction'empty'isrequiredtobe utilized.mailmsg.cpp40 Theerrorhereisthis:thevector::empty()functioniscalledbymistakeinsteadofvector::clear(),and thearray'scontentsremainthesame.Itisaveryfrequenterrorbecausethewords'clear'and'empty' arerathercloseinmeaning,andyoumighteasilymixthemup. Example 4. WinMergeproject.Using'empty'functioninsteadof'clear'.


C ollapse|C opyC ode

voidCDirView::GetItemFileNames(intsel, String&strLeft,String&strRight)const { UINT_PTRdiffpos=GetItemKey(sel) if(diffpos==(UINT_PTR)SPECIAL_ITEM_POS) { strLeft.empty() strRight.empty()

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

} else { ... } }

TheerrorwasfoundthroughtheV530diagnostic:Thereturnvalueoffunction'empty'isrequiredtobe utilizedWinMergeDirActions.cpp1307,1308 Again,thereasonisinusingtheempty()functioninsteadofclear().Wecouldciteexamplesofsuch errorsfromotherprojectsaswell:InstantVNC,IPPSamples,Chromium,IntelAMTSDK,etc. Unfortunately,allthesesamplesarealike,andthereisnothinginterestingaboutexaminingthem.But trustme,youcanseethesedefectsinseriousprojectsdevelopedbyprofessionalprogrammers. Example 5. Pixieproject.Using'alloca'functioninsideloops.


C ollapse|C opyC ode

inlinevoidtriangulatePolygon(...){ ... for(i=1i<nloopsi++){ ... do{ ... do{ ... CTriVertex*snVertex= (CTriVertex*)alloca(2*sizeof(CTriVertex)) ... }while(dVertex!=loops[0]) ... }while(sVertex!=loops[i]) ... } ... }

TheerrorwasfoundthroughtheV505diagnostic:The'alloca'functionisusedinsidetheloop.Thiscan quicklyoverflowstack.ripolygons.cpp1120 Theallocafunctionallocatesmemoryinsidethestack,socallingitmanytimesinsidetheloopbodymay suddenlycauseastackoverflow.Andwehaveseveralnestedloopshere.Thiscodemayexhauststack memoryveryquickly.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Example 6. MirandaIMproject.Argumentsmixedup.
C ollapse|C opyC ode

staticBOOLImageArray_Alloc(LP_IMAGE_ARRAY_DATAiad,intsize) { ... memset(&iad>nodes[iad>nodes_allocated_size], (size_growiad>nodes_allocated_size)* sizeof(IMAGE_ARRAY_DATA_NODE), 0) ... }

TheerrorwasfoundthroughtheV575diagnostic:Functionreceivesanoddargument.clist_modern modern_image_array.cpp59 The'memset'functionhandles0items,i.e.actuallydoesnothing.Thereasonisinmixeduparguments. Thisishowthecorrectcallofthememsetfunctionshouldbewritten:


C ollapse|C opyC ode

memset(&iad>nodes[iad>nodes_allocated_size], 0, (size_growiad>nodes_allocated_size)* sizeof(IMAGE_ARRAY_DATA_NODE))

Examples of meaningless code


Example 1.IPPSamplesproject.Incompletecondition.
C ollapse|C opyC ode

voidlNormalizeVector_32f_P3IM(Ipp32f*vec[3], Ipp32s*mask,Ipp32slen) { Ipp32si Ipp32fnorm for(i=0i<leni++){ if(mask<0)continue norm=1.0f/sqrt(vec[0][i]*vec[0][i]+ vec[1][i]*vec[1][i]+vec[2][i]*vec[2][i]) vec[0][i]*=normvec[1][i]*=normvec[2][i]*=norm } }

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

TheerrorwasfoundthroughtheV503diagnostic:Thisisanonsensicalcomparison:pointer<0. ipprsampleippr_sample.cpp501 Idonotknowhowithappened,butthereare3characters"[i]"missinginthiscode.Asaresult,the codeperformsameaninglesscheckthatthepointerisbelowzeroinsteadofcheckingthemaskarray. Thecorrectcheckshouldbewritteninthisway:if(mask[i]<0). Example 2. PcPs2Emulatorproject.Incorrectswitch.


C ollapse|C opyC ode

LRESULTCALLBACKIOP_DISASM(...) { ... switch(LOWORD(wParam)) { case(IDOK||IDCANCEL): EndDialog(hDlg,TRUE) return(TRUE) break } ... }

TheerrorwasfoundthroughtheV560diagnostic:Apartofconditionalexpressionisalwaystrue:2. pcsx2debugger.cpp321 Thiscodedoesnothaveanymeaning.Theprogrammermusthaveintendedtowriteitthisway:


C ollapse|C opyC ode

switch(LOWORD(wParam)) { caseIDOK://nobreak caseIDCANCEL: EndDialog(hDlg,TRUE) return(TRUE) break }

Example 3. CPUIdentifyingToolproject.Atoostrictcondition.
C ollapse|C opyC ode

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

voidprojillum(short*wtab,intxdots,intydots,doubledec) { ... s=sin(dtr(dec)) x=s*sin(th) y=cos(th) ... lon=(y==0&&x==0)?0.0:rtd(atan2(y,x)) }

TheerrorwasfoundthroughtheV550diagnostic:Anoddprecisecomparison:x==0.It'sprobably bettertouseacomparisonwithdefinedprecision:fabs(AB)'<'Epsilon.clock_dllsunalgo.cpp155 Itisstrangetoexpectthattheresultwillbestrictly0afterexecutingallthesecomplexcalculations using'sin'and'cos'functions.Mostlikely,theremustbecomparisontobeperformedwithcertain accuracy. Example 4. Lugaru.Doubleassignment.


C ollapse|C opyC ode

intGame::DrawGLScene(void) { ... radius=fast_sqrt(maxdistance) radius=110 ... }

TheerrorwasfoundthroughtheV519diagnostic:The'radius'objectisassignedvaluestwice successively.Perhapsthisisamistake.Lugarugamedraw.cpp1505 Theprogrammermusthavedeliberatelywrittenvalue110intothe'radius'variableforthesakeof experimentandthenforgottoremovethisline.Asaresult,wehaveameaninglessandmaybeeven invalidcode. Example 5. QTproject.Duplicatedcheck.


C ollapse|C opyC ode

Q3TextCustomItem*Q3TextDocument::parseTable(...) { ... while(end<length &&!hasPrefix(doc,length,end,QLatin1String("</td"))

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

&&!hasPrefix(doc,length,end,QLatin1String("<td")) &&!hasPrefix(doc,length,end,QLatin1String("</th")) &&!hasPrefix(doc,length,end,QLatin1String("<th")) &&!hasPrefix(doc,length,end,QLatin1String("<td")) &&!hasPrefix(doc,length,end,QLatin1String("</tr")) &&!hasPrefix(doc,length,end,QLatin1String("<tr")) &&!hasPrefix(doc,length,end,QLatin1String("</table"))){ ... }

TheerrorwasfoundthroughtheV501diagnostic:Thereareidenticalsubexpressionstotheleftandto therightofthe'&&'operator.Qt3Supportq3richtext.cpp6978 Presenceofthe"<td"prefixischeckedtwiceinthecondition.Itismeaningless.Maybeitisanextra checkorthereshouldbesomeotherprefixinsteadofthesecond"<td". Example 6. Audacityproject.Strangecheck.


C ollapse|C opyC ode

intsf_error(SNDFILE*sndfile) { ... if(!sndfile) { if(sf_error!=0) returnsf_errno return0 } ... }

TheerrorwasfoundthroughtheV516diagnostic:Considerinspectinganoddexpression.Nonnull functionpointeriscomparedtonull:'sf_error!=0'.libsndfilesndfile.c491 The"sf_error!=0"checkalwaysreturnstrue,since'sf_error'isthenameofthefunctioninwhichthe codeisexecuted. Example 7. IPPSamplesproject.Strangecodeinsidealoop.


C ollapse|C opyC ode

staticIppStatusmp2_HuffmanTableInitAlloc(Ipp32s*tbl,...) {

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

... for(i=0i<num_tbli++){ *tbl++ } ... }

TheerrorwasfoundthroughtheV532diagnostic:Considerinspectingthestatementof'*pointer++' pattern.Probablymeant:'(*pointer)++'.mpeg2_decumc_mpeg2_dec.cpp59 Theloopbodyisprobablyincompletebecauseitismeaninglessinthecurrentform.

Always true or always false conditions


Itisaverylargeandwidelyspreadtypeoferrors.Theseerrorsalsovarygreatlydependingonthe importancelevel.TonondangerouserrorswemayreferincorrectconditionsinASSERTthatactuallydo notcheckanything.Todangerouserrors,incorrectchecksofbuffersizeorindexsizearereferred. Example 1. Shareazaproject.Valuerangeofchartype.
C ollapse|C opyC ode

voidCRemote::Output(LPCTSTRpszName) { ... CHAR*pBytes=newCHAR[nBytes] hFile.Read(pBytes,nBytes) ... if(nBytes>3&&pBytes[0]==0xEF&& pBytes[1]==0xBB&&pBytes[2]==0xBF) { pBytes+=3 nBytes=3 bBOM=true } ... }

TheerrorwasfoundthroughtheV547diagnostic:Expression'pBytes[0]==0xEF'isalwaysfalse.The valuerangeofsignedchartype:[128,127].Shareazaremote.cpp350 Inthiscode,the'TCHAR'typeisthe'char'type.Thevaluerangeofcharisfrom128to127inclusive. Value0xEFinthevariableofthechartypeisnothingelsethannumber17.Whencomparingthechar

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

variablewithnumber0xEF,itstypeisextendeduptothe'int'type.Butthevaluestillliesinsidethe range[128..127].The"pBytes[0]==0xEF"("17==0xEF")conditionisalwaysfalse,andtheprogram doesnotworkasintended. Thisisthecorrectcomparison:


C ollapse|C opyC ode

if(nBytes>3&&pBytes[0]==TCHAR(0xEF)&& pBytes[1]==TCHAR(0xBB)&& pBytes[2]==TCHAR(0xBF))

Example 2. TortoiseSVNproject.Valuerangeofchartype.
C ollapse|C opyC ode

BOOLTortoiseBlame::OpenFile(constTCHAR*fileName) { ... //checkeachlineforillegalutf8sequences. //Ifoneisfound,wetreat //thefileasASCII,otherwiseweassume //anUTF8file. char*utf8CheckBuf=lineptr while((bUTF8)&&(*utf8CheckBuf)) { if((*utf8CheckBuf==0xC0)|| (*utf8CheckBuf==0xC1)|| (*utf8CheckBuf>=0xF5)) { bUTF8=false break } ... } ... }

TheerrorwasfoundthroughtheV547diagnostic:Expression'*utf8CheckBuf==0xC0'isalwaysfalse. Thevaluerangeofsignedchartype:[128,127].tortoiseblame.cpp310 Whilethedefectinthepreviousexampleseemstobecausedthroughmereinattention,inthiscaseitis notso.Hereisanotheridenticalexamplewhereaconditionisalwaysfalse.Thisisaverywidelyspread typeoferrorsinvariousprojects.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Example 3. VirtualDubproject.Unsignedtypeisalways>=0.
C ollapse|C opyC ode

typedefunsignedshortwint_t ... voidlexungetc(wint_tc){ if(c<0) return g_backstack.push_back(c) }

TheerrorwasfoundthroughtheV547diagnostic:Expression'c<0'isalwaysfalse.Unsignedtypevalue isnever<0.Amilexer.cpp225 The"c<0"conditionisalwaysfalsebecausethevariableoftheunsignedtypeisalwaysaboveorequal to0. Example 4. SwissArmyKnifeofTraceproject.Sockethandling.


C ollapse|C opyC ode

staticUINT_PTRm_socketHandle voidTTrace::LoopMessages(void) { ... //Socketcreation if((m_socketHandle=socket(AF_INET,SOCK_STREAM,0))<0) { continue } ... }

TheerrorwasfoundthroughtheV547diagnostic:Expression'(m_socketHandle=socket(2,1,0))<0' isalwaysfalse.Unsignedtypevalueisnever<0.Vs8_Win_Libtracetool.cpp871 Anattempttocheckthatasocketwascreatedsuccessfullyisperformedincorrectly.Ifasocketcannot becreated,thissituationisnothandledinanyway.Tomakethecheckworkcorrectly,weshoulduse theINVALID_SOCKETconstant:


C ollapse|C opyC ode

m_socketHandle=socket(AF_INET,SOCK_STREAM,0)

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

if(m_socketHandle==INVALID_SOCKET)

Example 5. Chromiumproject.Timehandling.
C ollapse|C opyC ode

IdleStateCalculateIdleState(...){ ... DWORDcurrent_idle_time=0 ... //Willgoveifwehavebeenidlefor //alongtime(2gbseconds). if(current_idle_time<0) current_idle_time=INT_MAX ... }

TheerrorwasfoundthroughtheV547diagnostic:Expression'current_idle_time<0'isalwaysfalse. Unsignedtypevalueisnever<0.browseridle_win.cc23 Tohandletime,avariableoftheunsignedtypeisused.Asaresult,checkoftoolargevaluesdoesnot work.Thisisthecorrectcode:


C ollapse|C opyC ode

if(current_idle_time>INT_MAX) current_idle_time=INT_MAX

Example 6. ICUproject.Errorincondition.
C ollapse|C opyC ode

U_CDECL_BEGINstaticconstchar*U_CALLCONV _processVariableTop(...) { ... if(i==locElementCapacity&& (*string!=0||*string!='_')) { *status=U_BUFFER_OVERFLOW_ERROR } ... }

TheerrorwasfoundthroughtheV547diagnostic:Expression'*string!=0||*string!='_''isalways

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

true.Probablythe'&&'operatorshouldbeusedhere.icui18nucol_sit.cpp242 Theconditioncontainsalogicalerror.The"(*string!=0||*string!='_')"subexpressionisalwaystrue. Itisimpossiblethatoneandthesamestringcharacterisnotequalto0and'_'atatime. Example 7. QTproject.Dangerousloop.


C ollapse|C opyC ode

boolequals(class1*val1,class2*val2)const{ { ... size_tsize=val1>size() ... while(size>=0){ if(!comp(*itr1,*itr2)) returnfalse itr1++ itr2++ } ... }

TheerrorwasfoundthroughtheV547diagnostic:Expression'size>=0'isalwaystrue.Unsignedtype valueisalways>=0.QtCLucenearrays.h154 The(size>=0)conditionisalwaystrue,sincethesizevariablehastheunsignedtype.Itmeansthat iftwosequencesbeingcomparedarealike,wewillgetanoverflowthatwillinitsturncauseAccess Violationorotherprogramfailures. Thisisthecorrectcode:


C ollapse|C opyC ode

for(size_ti=0i!=sizei++){ if(!comp(*itr1,*itr2)) returnfalse itr1++ itr2++ }

Example 8. MySQLproject.Errorincondition.
C ollapse|C opyC ode

enumenum_mysql_timestamp_type

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

str_to_datetime(...) { ... elseif(str[0]!='a'||str[0]!='A') continue/*NotAM/PM*/ ... }

TheerrorwasfoundthroughtheV547diagnostic:Expression'str[0]!='a'||str[0]!='A''isalways true.Probablythe'&&'operatorshouldbeusedhere.clientlibmy_time.c340 Theconditionisalwaystruebecausethecharacterisalwayseithernotequalto'a'orto'A'.Thisisthe correctcheck:


C ollapse|C opyC ode

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

Example 9. QTproject.Incorrectcountofreferences.
C ollapse|C opyC ode

STDMETHODIMPQEnumPins::QueryInterface(constIID&iid,void**out) { ... if(S_OK) AddRef() returnhr }

TheerrorwasfoundthroughtheV545diagnostic:Suchconditionalexpressionof'if'operatorisincorrect fortheHRESULTtypevalue'(HRESULT)0L'.TheSUCCEEDEDorFAILEDmacroshouldbeusedinstead. phonon_ds9qbasefilter.cpp60 ThecheckconditionisrepresentedbytheS_OKconstant.SinceS_OKis0,theAddRef()functionwill neverbecalled.Thisishowthischeckmustlook:if(hr==S_OK). Example 10. TickerTapeproject.Incorrecttornado.


C ollapse|C opyC ode

voidGetWindAtSingleTornado(...) { ... if(radius<THRESH*5)

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

*yOut=THRESH*10/radius elseif(radius<THRESH*5) *yOut=3.0f/(THRESH*5.0f)* (radiusTHRESH*5.0f)+3.0f else *yOut=0.0f ... }

TheerrorwasfoundthroughtheV517diagnostic:Theuseof'if(A){...}elseif(A){...}'patternwas detected.Thereisaprobabilityoflogicalerrorpresence.TickerTapewind.cpp118 Thesecondconditionisalwaysfalse.Thereasonisthatthefirstconditioncoincideswiththesecond. Theremustbeamisprinthere. Example 11. ApacheHTTPServerproject.ErrorofsockethandlinginWindows.


C ollapse|C opyC ode

typedefUINT_PTRSOCKET staticunsignedint__stdcallwin9x_accept(void*dummy) { SOCKETcsd ... do{ clen=sizeof(sa_client) csd=accept(nsd,(structsockaddr*)&sa_client,&clen) }while(csd<0&&APR_STATUS_IS_EINTR(apr_get_netos_error())) ... }

TheerrorwasfoundthroughtheV547diagnostic:Expression'csd<0'isalwaysfalse.Unsignedtype valueisnever<0.libhttpdchild.c404 SockethandlingerrorsveryoftenemergeincrossplatformprogramsbuiltunderWindows.InLinux, socketdescriptorsarerepresentedbythesignedtype,whileinWindowsitistheunsignedtype. Programmersoftenforgetaboutthisandchecktheerrorstatusbycomparingthevalueto0.Thisis incorrectyoumustusespecializedconstants. Example 12. QTproject.Misprintincomparisons.


C ollapse|C opyC ode

QStringListProFileEvaluator::Private::values(...)

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

{ ... elseif(ver==QSysInfo::WV_NT) ret=QLatin1String("WinNT") elseif(ver==QSysInfo::WV_2000) ret=QLatin1String("Win2000") elseif(ver==QSysInfo::WV_2000)<< ret=QLatin1String("Win2003") elseif(ver==QSysInfo::WV_XP) ret=QLatin1String("WinXP") ... }

TheerrorwasfoundthroughtheV517diagnostic:Theuseof'if(A){...}elseif(A){...}'patternwas detected.Thereisaprobabilityoflogicalerrorpresence.Checklines:2303,2305.lrelease profileevaluator.cpp2303 Inthestringwehavemarked,theremustbethetext"ver==QSysInfo::WV_2003".Becauseofthis error,the"ret=QLatin1String("Win2003")"statementwillneverbeexecuted.

Code vulnerabilities
Ofcourse,errorsleadingtocodevulnerabilitiesareactuallymisprints,incorrectconditionsandincorrect arrayhandling.Butwedecidedtosingleoutcertainerrorsintoaseparategroupbecausetheyrelateto thenotionofsoftwarevulnerabilities.Anintruder,usingsucherrors,cantrytodisturbprogram operation,performanattacktogainextendedrightsorcarryoutanyotheractionshe/sheneeds. Example 1. UltimateTCP/IPproject.Incorrectcheckofanemptystring.
C ollapse|C opyC ode

char*CUT_CramMd5::GetClientResponse(LPCSTRServerChallenge) { ... if(m_szPassword!=NULL) { ... if(m_szPassword!='\0') { ... }

TheerrorwasfoundthroughtheV528diagnostic:Itisoddthatpointerto'char'typeiscomparedwith the'\0'value.Probablymeant:*m_szPassword!='\0'.UTMailut_crammd5.cpp333

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

ThiscodefragmentmustcheckthatthepointertothepasswordisnotequaltoNULLandthatthestring isnotempty.Butinstead,thecodecheckstwicethatthepointerisnotequaltoNULL.Thecheckofthe stringdoesnotwork.The"if(m_szPassword!='\0')"conditionwasintendedtocheckthatthereisa terminalnullintheverybeginningofthestring,whichmeansthatthestringisempty.Butapointer dereferencingoperationismissinghere,anditisthepointeritselfwhichiscomparedtozero.Thisisthe correctcode:


C ollapse|C opyC ode

if(m_szPassword!=NULL) { ... if(*m_szPassword!='\0')

Example 2. Chromiumproject.Nullpointerhandling.
C ollapse|C opyC ode

boolChromeFrameNPAPI::Invoke(...) { ChromeFrameNPAPI*plugin_instance= ChromeFrameInstanceFromNPObject(header) if(!plugin_instance&& (plugin_instance>automation_client_.get())) returnfalse ... }

TheerrorwasfoundthroughtheV522diagnostic:Dereferencingofthenullpointer'plugin_instance' mighttakeplace.Checkthelogicalcondition.chrome_frame_npapichrome_frame_npapi.cc517 Theconditionthatchecksthenullpointeriswrittenincorrectly.Asaresult,wehaveasegmentation error.Thisisthecorrectcode:


C ollapse|C opyC ode

if(plugin_instance&& (plugin_instance>automation_client_.get())) returnfalse

Example 3. SMTPClientwithSSL/TLSproject.Incompletebufferclearing.
C ollapse|C opyC ode

voidMD5::finalize(){

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

... uint1buffer[64] ... //Zeroizesensitiveinformation memset(buffer,0,sizeof(*buffer)) ... }

TheerrorwasfoundthroughtheV512diagnostic:Acallofthe'memset'functionwillleadtoabuffer overfloworunderflow.CSmtpmd5.cpp212 Forsecuritypurposes,thefunctiontriestoclearthebuffercontainingsensitiveinformation.Butitfails. Onlythefirstbytewillbeclearedinthebuffer.Theerroristhis:the'sizeof'operatorcalculatesthesize ofthe'uint1'typeinsteadofbuffer.Thisisthecorrectcode:


C ollapse|C opyC ode

memset(buffer,0,sizeof(buffer))

Generally,errorsofincompletememoryclearingareratherfrequent.Considersomeothercaseslikethis. Example 4. Chromium.Incompletebufferclearing.


C ollapse|C opyC ode

voidTime::Explode(...,Exploded*exploded)const{ ... ZeroMemory(exploded,sizeof(exploded)) ... }

TheerrorwasfoundthroughtheV512diagnostic:Acallofthe'memset'functionwillleadtounderflow ofthebuffer'(exploded)'.basetime_win.cc227 TheZeroMemoryfunctionclearsonlypartoftheExplodedstructure.Thereasonisthatthe'sizeof' operatorreturnsthepointersize.Tofixtheerror,wemustdereferencethepointer:


C ollapse|C opyC ode

ZeroMemory(exploded,sizeof(*exploded))

Example 5. ApacheHTTPServerproject.Incompletebufferclearing.
C ollapse|C opyC ode

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

#defineMEMSET_BZERO(p,l)memset((p),0,(l)) voidapr__SHA256_Final(...,SHA256_CTX*context){ ... MEMSET_BZERO(context,sizeof(context)) ... }

TheerrorwasfoundthroughtheV512diagnostic:Acallofthe'memset'functionwillleadtounderflow ofthebuffer'(context)'.aprsha2.c560 Theerroriscompletelyidenticaltothepreviousone.The'sizeof'operatorcalculatesthepointersize.To fixit,wemustwrite:"sizeof(*context)". Example 6. MirandaIMproject.Incorrectstringhandling.


C ollapse|C opyC ode

staticchar*_skipblank(char*str) { char*endstr=str+strlen(str) while((*str==''||*str=='\t')&&str!='\0')str++ while((*endstr==''||*endstr=='\t')&& endstr!='\0'&&endstr<str) endstr ... }

Theerrorwasfoundthroughthediagnostics:V528Itisoddthatpointerto'char'typeiscomparedwith the'\0'value.Probablymeant:*str!='\0'.clist_modernmodern_skinbutton.cpp282 V528Itisoddthatpointerto'char'typeiscomparedwiththe'\0'value.Probablymeant:*endstr!= '\0'.clist_modernmodern_skinbutton.cpp283 Thiscodeisratherdangerousbecauseitincorrectlydeterminesthestringend.Itmaycauseastring overflowand,asaconsequence,anAccessViolationexception.Theerrorlieshere:"str!='\0'"andhere: "endstr!='\0'".Apointerdereferencingoperationismissing.Thisisthecorrectcode:


C ollapse|C opyC ode

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

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Example 7. PNGlibraryproject.Accidentalpointerclearing.
C ollapse|C opyC ode

png_size_t png_check_keyword(png_structppng_ptr,png_charpkey, png_charppnew_key) { ... if(key_len>79) { png_warning(png_ptr,"keywordlengthmustbe179characters") new_key[79]='\0' key_len=79 } ... }

TheerrorwasfoundthroughtheV527diagnostic:Itisoddthatthe'\0'valueisassignedto'char'type pointer.Probablymeant:*new_key[79]='\0'.graphics3Dpngwutil.c1283 Thissampledemonstratesamistakewhentheprogrammeraccidentallyclearsthepointerinsteadof truncatingthestringlength.Thepointisthat'new_key'isapointertoastring.Anditmeansthatwe shouldwriteourcodeasfollowstotruncateitto79characters:


C ollapse|C opyC ode

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

Example 8. IntelAMTSDKproject.Unverifiedusername.
C ollapse|C opyC ode

staticvoid wsman_set_subscribe_options(...) { ... if(options>delivery_certificatethumbprint|| options>delivery_password|| options>delivery_password){ ... }

TheerrorwasfoundthroughtheV501diagnostic:Thereareidenticalsubexpressions'options >delivery_password'totheleftandtotherightofthe'||'operator.OpenWsmanLibwsmanclient.c631

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Becauseofthedeveloper'sinattention,presenceofpasswordischeckedtwice,whilepresenceofuser nameisnotcheckedatall.Thisisthecorrectcode:
C ollapse|C opyC ode

if(options>delivery_certificatethumbprint|| options>delivery_username|| options>delivery_password){

Example 9. UltimateTCP/IPproject.Incorrecthandlingofemptystrings.
C ollapse|C opyC ode

voidCUT_StrMethods::RemoveCRLF(LPSTRbuf) { //v4.2changedtosize_t size_tlen,indx=1 if(buf!=NULL){ len=strlen(buf) while((lenindx)>=0&&indx<=2){ if(buf[lenindx]=='\r'|| buf[lenindx]=='\n') buf[lenindx]=0 ++indx } } }

TheerrorwasfoundthroughtheV547diagnostic:Expression'(lenindx)>=0'isalwaystrue.Unsigned typevalueisalways>=0.UTDnsutstrlst.cpp58 The"lenindx"expressionhastheunsignedtype'size_t'andisalways>=0.Let'slookwhatitwillresult in,ifwesendanemptystringtotheinput. Ifthestringisempty,then:len=0,indx=1. Thelenindxexpressionisequalto0xFFFFFFFFu. Since0xFFFFFFFFu>0andindx<=2,anarrayaccessisperformed "buf[lenindx]". The"buf[0xFFFFFFFFu]"operationwillcauseAccessViolation. Example 10. MirandaIMproject.Underflowprotectiondoesnotwork.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

C ollapse|C opyC ode

voidAppend(PCXSTRpszSrc,intnLength) { ... UINTnOldLength=GetLength() if(nOldLength<0) { //protectsfromunderflow nOldLength=0 } ... }

TheerrorwasfoundthroughtheV547diagnostic:Expression'nOldLength<0'isalwaysfalse.Unsigned typevalueisnever<0.IRCmstring.h229 Thecheck"if(nOldLength<0)"doesnotworksincethenOldLengthvariablehastheunsignedtype. Example 11. ApacheHTTPServerproject.Incorrecthandlingofnegativevalues.


C ollapse|C opyC ode

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

TheerrorwasfoundthroughtheV547diagnostic:Expression'len<0'isalwaysfalse.Unsignedtype valueisnever<0.aprutilapr_memcache.c814 Thecheck"if(len<0)"doesnotworkbecausethe'len'variablehastheunsignedtype.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Example 12. UltimateTCP/IPproject.Incorrectconditionoflooptermination.


C ollapse|C opyC ode

voidCUT_StrMethods::RemoveSpaces(LPSTRszString){ ... size_tloop,len=strlen(szString) //Removethetrailingspaces for(loop=(len1)loop>=0loop){ if(szString[loop]!='') break } ... }

TheerrorwasfoundthroughtheV547diagnostic:Expression'loop>=0'isalwaystrue.Unsignedtype valueisalways>=0.UTDnsutstrlst.cpp430 Supposethewholestringconsistsonlyofspaces.Whilesearchingthecharacters,theprogramwillreach thenullitemofthestring,andthe'loop'variablewillequaltozero.Thenitwillbedecrementedonce again.Sincethisvariableisofunsignedtype,itsvaluewillbe0xFFFFFFFFuor0xFFFFFFFFFFFFFFFFu (dependingonthearchitecture).Thisvalueis'naturally>=0',andanewloopiterationwillstart.There willbeanattemptofmemoryaccessbyszString[0xFFFFFFFFu]addresstheconsequencesofthisare familiartoeveryC/C++programmer.

Copy-Paste
DevelopersshouldnotalsounderestimateCopyPasteerrorsaswellascommonmisprints.Theyare veryverynumerous.Programmersspendmuchtimeondebuggingthem. Ofcourse,misprintsandCopyPasteerrorsaresimilar,butthereisadifferencebetweenthemthat causedustoplacethemintodifferentgroupsinthisarticle.Misprintsoftenresultinusingawrong variableinsteadoftheneededone.Andinthecaseofcopypaste,programmerssimplyforgettoedit copiedandpastedlines. Example 1. FennecMediaProjectproject.Mistakewhilehandlingarrayitems.
C ollapse|C opyC ode

void*tag_write_setframe(char*tmem, constchar*tid,conststringdstr) { ... if(lset)

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

{ fhead[11]='\0' fhead[12]='\0' fhead[13]='\0' fhead[13]='\0' } ... }

TheerrorwasfoundthroughtheV525diagnostic:Thecodecontainingthecollectionofsimilarblocks. Checkitems'11','12','13','13'inlines716,717,718,719.id3editor.c716 Thefoursimilarlinesmusthaveappearedinthecodethroughthecopypastemethod.Whenthe programmerstartededitingtheindexes,he/shemadeamistakethatcauseszerotobewritteninto 'fhead[13]'twiceandnotbewritteninto'fhead[14]'. Example 2. MySQLproject.Mistakewhilehandlingarrayitems.


C ollapse|C opyC ode

staticintrr_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] }

TheerrorwasfoundthroughtheV525diagnostic:Thecodecontainingthecollectionofsimilarblocks. Checkitems'0','1','2','3','4','1','6'inlines680,682,684,689,691,693,695.sqlrecords.cc680 Itisnotapparentatfirstsight,solet'ssingleitout:


C ollapse|C opyC ode

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

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

Actuallytheremustbethefollowingcode:
C ollapse|C opyC ode

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

Example 3. TortoiseSVNproject.Filenamenotcorrected.
C ollapse|C opyC ode

BOOLGetImageHlpVersion(DWORD&dwMS,DWORD&dwLS) { return(GetInMemoryFileVersion(("DBGHELP.DLL"), dwMS, dwLS)) } BOOLGetDbgHelpVersion(DWORD&dwMS,DWORD&dwLS) { return(GetInMemoryFileVersion(("DBGHELP.DLL"), dwMS, dwLS)) }

TheerrorwasfoundthroughtheV524diagnostic:Itisoddthatthe'GetDbgHelpVersion'functionisfully equivalenttothe'GetImageHlpVersion'function(SymbolEngine.h,line98).symbolengine.h105 The'GetImageHlpVersion'functionmusthaveappearedthroughcopyingandpastingthe 'GetInMemoryFileVersion'function.Theerroristhis:theprogrammerforgottofixthefilenameinthe copiedandpastedfunction.Thisisthecorrectcode:


C ollapse|C opyC ode

BOOLGetImageHlpVersion(DWORD&dwMS,DWORD&dwLS) { return(GetInMemoryFileVersion(("IMAGEHLP.DLL"), dwMS, dwLS)) }

Example 4. Clangproject.Identicalfunctionbodies.
C ollapse|C opyC ode

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

MapTyPerPtrTopDown MapTyPerPtrBottomUp voidclearBottomUpPointers(){ PerPtrTopDown.clear() } voidclearTopDownPointers(){ PerPtrTopDown.clear() }

TheerrorwasfoundthroughtheV524diagnostic:Itisoddthatthebodyof'clearTopDownPointers' functionisfullyequivalenttothebodyof'clearBottomUpPointers'function(ObjCARC.cpp,line1318). LLVMScalarOptsobjcarc.cpp1322 ThebodyoftheclearBottomUpPointersfunctionseemstobeincorrectthisfunctionshouldbewritten asfollows:


C ollapse|C opyC ode

voidclearBottomUpPointers(){ PerPtrBottomUp.clear() }

Example 5. QT.Unsuccessfulswap.
C ollapse|C opyC ode

boolqt_testCollision(...) { ... t=x1x1=x2x2=t t=y1x1=y2y2=t ... }

TheerrorwasfoundthroughtheV519diagnostic:The'x1'variableisassignedvaluestwice successively.Perhapsthisisamistake.Checklines:2218,2219.Qt3Supportq3canvas.cpp2219 Thefirstlineisabsolutelycorrectandswapsvaluesinthex1andx2variables.Inthesecondline, variablesy1andy2mustbeswapped.Thislineisprobablyacopyofthepreviousone.Allthe'x'letters mustbereplacedwithletters'y'.Unfortunately,theprogrammerforgottodothatinoneplace:"... x1=y2...".

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Correctcode:
C ollapse|C opyC ode

t=x1x1=x2x2=t t=y1y1=y2y2=t

Example 6. CrystalSpace3DSDKproject.Identicalsubexpressions.
C ollapse|C opyC ode

inline_boolContains(constLSS&lss) { returnContains(Sphere(lss.mP0,lss.mRadius))&& Contains(Sphere(lss.mP0,lss.mRadius)) }

TheerrorwasfoundthroughtheV501diagnostic:Thereareidenticalsubexpressionstotheleftandto therightofthe'&&'operator.plgcsopcodeicelss.h69 Theerroristhis:the'lss.mP0.'variableisusedtwicehere.Theremustbe'lss.mP1'inthefirstpartofthe expression. Example 7. Notepad++project.Settinganincorrectstyle.


C ollapse|C opyC ode

voidKeyWordsStyleDialog::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)

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

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) ... }

TheerrorwasfoundthroughtheV525diagnostic:Thecodecontainingthecollectionofsimilarblocks. Checkitems'7','7','6','7'inlines576,580,584,588 Itisalmostunrealtofindthiserrorbysight,solet'sabridgethetexttosingleoutthemostinteresting fragments:


C ollapse|C opyC ode

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, ...)

Bymistake,IDC_KEYWORD3_BOLD_CHECKisusedinsteadofIDC_KEYWORD3_ITALIC_CHECK. Example 8. ReactOSobject.Choosingawrongobject.


C ollapse|C opyC ode

voidCardButton::DrawRect(HDChdc,RECT*rect,boolfNormal) { ... HPENhhi=CreatePen(0,0,MAKE_PALETTERGB(crHighlight)) HPENhsh=CreatePen(0,0,MAKE_PALETTERGB(crShadow))

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

... if(fNormal) hOld=SelectObject(hdc,hhi) else hOld=SelectObject(hdc,hhi) ... }

TheerrorwasfoundthroughtheV523diagnostic:The'then'statementisequivalenttothe'else' statement.cardlibcardbutton.cpp83 The'hsh'objectisnotused,while'hhi'isusedtwice.Thisisthecorrectcode:


C ollapse|C opyC ode

if(fNormal) hOld=SelectObject(hdc,hhi) else hOld=SelectObject(hdc,hsh)

Example 9. IPPSamplesproject.Incorrectcheck.
C ollapse|C opyC ode

StatusVC1VideoDecoder::ResizeBuffer() { ... if(m_pContext&&m_pContext>m_seqLayerHeader&& m_pContext>m_seqLayerHeader>heightMB&& m_pContext>m_seqLayerHeader>heightMB) ... }

TheerrorwasfoundthroughtheV501diagnostic:Thereareidenticalsubexpressions'm_pContext >m_seqLayerHeader>heightMB'totheleftandtotherightofthe'&&'operator.vc1_dec umc_vc1_video_decoder.cpp1347 Correctcode:


C ollapse|C opyC ode

if(m_pContext&&m_pContext>m_seqLayerHeader&& m_pContext>m_seqLayerHeader>heightMB&& m_pContext>m_seqLayerHeader>widthMB)

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Example 10. ReactOSproject.Mistakeinavariablename.


C ollapse|C opyC ode

BOOLAPIENTRY GreStretchBltMask(...) { ... MaskPoint.x+=DCMask>ptlDCOrig.x MaskPoint.y+=DCMask>ptlDCOrig.x ... }

TheerrorwasfoundthroughtheV537diagnostic:Considerreviewingthecorrectnessof'x'item'susage. win32kbitblt.c670 Thisisaverygoodexamplewhereyoucanseethatalinewascopiedandpasted.Afterthat,the programmerfixedthefirstname'x'butforgottofixthesecond.Thisisthecorrectcode:


C ollapse|C opyC ode

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

Miscellaneous
Example 1. ImageProcessingSDKproject.Octalnumber.
C ollapse|C opyC ode

inline voidelxLuminocity(constPixelRGBus&iPixel, LuminanceCell<PixelRGBus>&oCell) { oCell._luminance=uint16(0.2220f*iPixel._red+ 0.7067f*iPixel._blue+0.0713f*iPixel._green) oCell._pixel=iPixel } inline voidelxLuminocity(constPixelRGBi&iPixel, LuminanceCell<PixelRGBi>&oCell) { oCell._luminance=2220*iPixel._red+ 7067*iPixel._blue+0713*iPixel._green oCell._pixel=iPixel

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

TheerrorwasfoundthroughtheV536diagnostic:Beadvisedthattheutilizedconstantvalueis representedbyanoctalform.Oct:0713,Dec:459.IFFpluginspixelservices.inl146 Ifyouexaminethesecondfunction,youwillseethattheprogrammerintendedtousenumber713,not 0713.Number0713isdeclaredintheoctalnumeralsystem.Youcaneasilyforgetaboutitifyouseldom useoctalconstants. Example 2. IPPSamplesproject.Onevariablefortwoloops.


C ollapse|C opyC ode

JERRCODECJPEGDecoder::DecodeScanBaselineNI(void) { ... for(c=0c<m_scan_ncompsc++) { block=m_block_buffer+(DCTSIZE2*m_nblock*(j+(i*m_numxMCU))) //skipanyrelevantcomponents for(c=0c<m_ccomp[m_curr_comp_no].m_comp_noc++) { block+=(DCTSIZE2*m_ccomp[c].m_nblocks) } ... }

TheerrorwasfoundthroughtheV535diagnostic:Thevariable'c'isbeingusedforthisloopandforthe outerloop.jpegcodecjpegdec.cpp4652 Oneandthesamevariableisusedfortheouterloopandtheinnerloop.Asaresult,thiscodewillhandle onlypartofthedataorcauseaneternalloop.

References
1. Feedback.http://www.viva64.com/en/aboutfeedback/ 2. Twitter.http://twitter.com/Code_Analysis

License
Thisarticle,alongwithanyassociatedsourcecodeandfiles,islicensedunderTheCodeProjectOpen License(CPOL)

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

About the Authors


Karpov Andrey AndreyKarpovistechnicalmanageroftheOOO"ProgramVerificationSystems" (CoLtd)companydevelopingthePVSStudiotoolwhichisapackageofstatic codeanalyzersintegratingintotheVisualStudiodevelopmentenvironment. PVSStudioisastaticanalyzerthatdetectserrorsinsourcecodeofC/C++ applications.Thereare3setsofrulesincludedintoPVSStudio: 1. Diagnosisof64biterrors(Viva64) 2. Diagnosisofparallelerrors(VivaMP) 3. Generalpurposediagnosis Awards:MVP,IntelBlackBelt AndreyKarpovisalsotheauthorofmanyarticlesonthetopicof64bitand parallelsoftwaredevelopment.TolearnmoreaboutthePVSStudiotooland sourcesconcerning64bitandparallelsoftwaredevelopment,pleasevisitthe www.viva64.comsite. Best Articles: Lessonsondevelopmentof64bitC/C++applications 64bits PVSStudioadvertisementstaticanalysisofC/C++code 20issuesofportingC++codeonthe64bitplatform PVSStudiovsChromium MypageonLinkedInsite:http://www.linkedin.com/pub/4/585/6a3 Email:karpov@viva64(dot)com

Architect ProgramVerification Systems,C oLtd RussianFederation Member FollowonTwitter

Evgeniy Ryzhkov

I'mworkingonPVSStudiostaticanalyzer.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

MyLinkedInprofile.

C EO ProgramVerification Systems,C oLtd RussianFederation Member

ArticleTop

SignUptovote Poor

Excellent Vote

Comments and Discussions

Refresh My vote of 5 LastVisit:19:0031Dec'99LastUpdate:5:202Nov'11 General News Suggestion Question Bug Answer Joke Rant Admin Joonhwan71 FirstPrevNext 5hrs 33mins ago 1

P ermalink| A dvertis e| P rivac y| M obile | Web0 1 | 2 .5 .1 1 1 0 3 1 .1

L ayout:fixed| fluid

A rtic leC opyright2 0 1 1 byKarpovA ndrey,E vgeniyRyzhkov E verythingels eC opyrightC odeP rojec t,1 9 9 9 2 0 1 1 T erms ofU s e

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

You might also like