Webcache Google User Content Com Search Sclient Psy Ab HL en B
Webcache Google User Content Com Search Sclient Psy Ab HL en B
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
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.
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/
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)
pdfcrowd.com
pdfcrowd.com
Figure1.Logosofprojectswehavechecked
ID_INLINEmat3_t::mat3_t(floatsrc[3][3]){ memcpy(mat,src,sizeof(src)) }
pdfcrowd.com
ID_INLINEmat3_t::mat3_t(float(&src)[3][3]) { memcpy(mat,src,sizeof(src)) }
Example 3.FARManagerproject.Onlypartofanarrayiscleared.
C ollapse|C opyC ode
pdfcrowd.com
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)
pdfcrowd.com
{ longrt0=cfd>m[9],gt0=cfd>m[9],bt0=cfd>m[9] ... }
pdfcrowd.com
bs>teamleader[sizeof(bs>teamleader)1]='\0'
Example 8.MirandaIMproject.Onlypartofastringiscopied.
C ollapse|C opyC ode
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{
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 } } ... }
for(i=0i<sizeof(doserrors)/sizeof(*doserrors)i++)
Example 10.CPUIdentifyingToolproject.Astringisprintedintoitself.
C ollapse|C opyC ode
pdfcrowd.com
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
#defineCONT_MAP_MAX50
pdfcrowd.com
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
pdfcrowd.com
... }
~auto_ptr(){ delete_Myptr }
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++ ... } ... }
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
pdfcrowd.com
pdfcrowd.com
((!create_info>options)&HA_LEX_CREATE_TMP_TABLE) Weshoulduseadditionalparenthesesifwewantthecodetoworkproperly:
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
pdfcrowd.com
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
pdfcrowd.com
Butactuallyitisequivalenttothefollowingconstruct:
C ollapse|C opyC ode
Example 5.IPPSamplesproject.Prioritiesof?:and|operations.
C ollapse|C opyC ode
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
pdfcrowd.com
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]) ... }
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
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]) ... }
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
pdfcrowd.com
pdfcrowd.com
boolNUW=LBO>hasNoUnsignedWrap()&&RBO>hasNoUnsignedWrap()
Example 4. Notepad++project.Incorrectstatetest.
C ollapse|C opyC ode
pdfcrowd.com
} ... }
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 ... }
transition>m_hasGetterSetterProperties= structure>m_hasGetterSetterProperties
Example 8. ApacheHTTPServerproject.Extrasizeofoperator.
pdfcrowd.com
sa>nLength=sizeof(SECURITY_ATTRIBUTES)
Example 9. FCEUltraproject.Doublevariabledeclaration.
C ollapse|C opyC ode
pdfcrowd.com
if(!fp) x=1
intsettings_default(void) { ...
pdfcrowd.com
intQCleanlooksStyle::pixelMetric(...) { ... casePM_SpinBoxFrameWidth: ret=3 break casePM_MenuBarItemSpacing: ret=6 casePM_MenuBarHMargin: ret=0 break ... }
intFindItem(...) { ...
pdfcrowd.com
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
pdfcrowd.com
} ... }
intJoiningProc(HWNDhwnd,UINTuMsg, WPARAMwParam,LPARAMlParam)
pdfcrowd.com
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
TheerrorwasfoundthroughtheV530diagnostic:Thereturnvalueoffunction'remove'isrequiredtobe
pdfcrowd.com
pdfcrowd.com
} else { ... } }
inlinevoidtriangulatePolygon(...){ ... for(i=1i<nloopsi++){ ... do{ ... do{ ... CTriVertex*snVertex= (CTriVertex*)alloca(2*sizeof(CTriVertex)) ... }while(dVertex!=loops[0]) ... }while(sVertex!=loops[i]) ... } ... }
pdfcrowd.com
Example 6. MirandaIMproject.Argumentsmixedup.
C ollapse|C opyC ode
pdfcrowd.com
Example 3. CPUIdentifyingToolproject.Atoostrictcondition.
C ollapse|C opyC ode
pdfcrowd.com
pdfcrowd.com
staticIppStatusmp2_HuffmanTableInitAlloc(Ipp32s*tbl,...) {
pdfcrowd.com
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 } ... }
pdfcrowd.com
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 } ... } ... }
pdfcrowd.com
Example 3. VirtualDubproject.Unsignedtypeisalways>=0.
C ollapse|C opyC ode
m_socketHandle=socket(AF_INET,SOCK_STREAM,0)
pdfcrowd.com
if(m_socketHandle==INVALID_SOCKET)
Example 5. Chromiumproject.Timehandling.
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
TheerrorwasfoundthroughtheV547diagnostic:Expression'*string!=0||*string!='_''isalways
pdfcrowd.com
boolequals(class1*val1,class2*val2)const{ { ... size_tsize=val1>size() ... while(size>=0){ if(!comp(*itr1,*itr2)) returnfalse itr1++ itr2++ } ... }
Example 8. MySQLproject.Errorincondition.
C ollapse|C opyC ode
enumenum_mysql_timestamp_type
pdfcrowd.com
elseif(str[0]!='a'&&str[0]!='A')
Example 9. QTproject.Incorrectcountofreferences.
C ollapse|C opyC ode
pdfcrowd.com
QStringListProFileEvaluator::Private::values(...)
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") ... }
Code vulnerabilities
Ofcourse,errorsleadingtocodevulnerabilitiesareactuallymisprints,incorrectconditionsandincorrect arrayhandling.Butwedecidedtosingleoutcertainerrorsintoaseparategroupbecausetheyrelateto thenotionofsoftwarevulnerabilities.Anintruder,usingsucherrors,cantrytodisturbprogram operation,performanattacktogainextendedrightsorcarryoutanyotheractionshe/sheneeds. Example 1. UltimateTCP/IPproject.Incorrectcheckofanemptystring.
C ollapse|C opyC ode
TheerrorwasfoundthroughtheV528diagnostic:Itisoddthatpointerto'char'typeiscomparedwith the'\0'value.Probablymeant:*m_szPassword!='\0'.UTMailut_crammd5.cpp333
pdfcrowd.com
Example 2. Chromiumproject.Nullpointerhandling.
C ollapse|C opyC ode
Example 3. SMTPClientwithSSL/TLSproject.Incompletebufferclearing.
C ollapse|C opyC ode
voidMD5::finalize(){
pdfcrowd.com
memset(buffer,0,sizeof(buffer))
ZeroMemory(exploded,sizeof(*exploded))
Example 5. ApacheHTTPServerproject.Incompletebufferclearing.
C ollapse|C opyC ode
pdfcrowd.com
pdfcrowd.com
Example 7. PNGlibraryproject.Accidentalpointerclearing.
C ollapse|C opyC ode
(*new_key)[79]='\0'
Example 8. IntelAMTSDKproject.Unverifiedusername.
C ollapse|C opyC ode
TheerrorwasfoundthroughtheV501diagnostic:Thereareidenticalsubexpressions'options >delivery_password'totheleftandtotherightofthe'||'operator.OpenWsmanLibwsmanclient.c631
pdfcrowd.com
Becauseofthedeveloper'sinattention,presenceofpasswordischeckedtwice,whilepresenceofuser nameisnotcheckedatall.Thisisthecorrectcode:
C ollapse|C opyC ode
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.
pdfcrowd.com
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{ ... } }
pdfcrowd.com
Copy-Paste
DevelopersshouldnotalsounderestimateCopyPasteerrorsaswellascommonmisprints.Theyare veryverynumerous.Programmersspendmuchtimeondebuggingthem. Ofcourse,misprintsandCopyPasteerrorsaresimilar,butthereisadifferencebetweenthemthat causedustoplacethemintodifferentgroupsinthisarticle.Misprintsoftenresultinusingawrong variableinsteadoftheneededone.Andinthecaseofcopypaste,programmerssimplyforgettoedit copiedandpastedlines. Example 1. FennecMediaProjectproject.Mistakewhilehandlingarrayitems.
C ollapse|C opyC ode
pdfcrowd.com
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] }
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
Example 4. Clangproject.Identicalfunctionbodies.
C ollapse|C opyC ode
pdfcrowd.com
voidclearBottomUpPointers(){ PerPtrBottomUp.clear() }
Example 5. QT.Unsuccessfulswap.
C ollapse|C opyC ode
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
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)
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) ... }
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, ...)
pdfcrowd.com
Example 9. IPPSamplesproject.Incorrectcheck.
C ollapse|C opyC ode
pdfcrowd.com
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
pdfcrowd.com
References
1. Feedback.http://www.viva64.com/en/aboutfeedback/ 2. Twitter.http://twitter.com/Code_Analysis
License
Thisarticle,alongwithanyassociatedsourcecodeandfiles,islicensedunderTheCodeProjectOpen License(CPOL)
pdfcrowd.com
Evgeniy Ryzhkov
I'mworkingonPVSStudiostaticanalyzer.
pdfcrowd.com
MyLinkedInprofile.
ArticleTop
SignUptovote Poor
Excellent Vote
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
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
pdfcrowd.com