information technology — programming languages — …...multiples of a byte address 3.1.3...

59
Baseline Edition TR 24772–3 © ISO/IEC 2017 – All rights reserved i ISO/IEC JTC 1/SC 22/WG23 N0770 Draft document for working group review Date: 2018-01-04 ISO/IEC TR 24772–3 Edition 1 ISO/IEC JTC 1/SC 22/WG 23 Secretariat: ANSI Information Technology — Programming languages — Guidance to avoiding vulnerabilities in programming languages – Part 3 – Vulnerability descriptions for the programming language C Élément introductif — Élément principal — Partie n: Titre de la partie Warning This document is not an ISO International Standard. It is distributed for review and comment. It is subject to change without notice and may not be referred to as an International Standard. Recipients of this draft are invited to submit, with their comments, notification of any relevant patent rights of which they are aware and to provide supporting documentation. Document type: International standard Document subtype: if applicable Document stage: (10) development stage Document language: E Deleted: 68 Formatted: Not Highlight Deleted: 40 Formatted: Highlight Deleted: 7-12 Deleted: 04 Deleted: -24 Deleted: 07

Upload: others

Post on 29-Sep-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

BaselineEdition TR24772–3

©ISO/IEC2017–Allrightsreserved i

ISO/IECJTC1/SC22/WG23N0770

DraftdocumentforworkinggroupreviewDate:2018-01-04

ISO/IECTR24772–3

Edition1

ISO/IECJTC1/SC22/WG23

Secretariat:ANSI

InformationTechnology—Programminglanguages—Guidancetoavoidingvulnerabilitiesinprogramminglanguages–Part3–VulnerabilitydescriptionsfortheprogramminglanguageC

Élémentintroductif—Élémentprincipal—Partien:Titredelapartie

Warning

ThisdocumentisnotanISOInternationalStandard.Itisdistributedforreviewandcomment.ItissubjecttochangewithoutnoticeandmaynotbereferredtoasanInternationalStandard.

Recipientsofthisdraftareinvitedtosubmit,withtheircomments,notificationofanyrelevantpatentrightsofwhichtheyareawareandtoprovidesupportingdocumentation.

Documenttype:InternationalstandardDocumentsubtype:ifapplicableDocumentstage:(10)developmentstageDocumentlanguage:E

Deleted: 68

Formatted: Not HighlightDeleted: 40

Formatted: HighlightDeleted: 7-12Deleted: 04Deleted: -24Deleted: 07

Page 2: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

ii ©ISO/IEC2017–Allrightsreserved

Copyrightnotice

ThisISOdocumentisaworkingdraftorcommitteedraftandiscopyright-protectedbyISO.WhilethereproductionofworkingdraftsorcommitteedraftsinanyformforusebyparticipantsintheISOstandardsdevelopmentprocessispermittedwithoutpriorpermissionfromISO,neitherthisdocumentnoranyextractfromitmaybereproduced,storedortransmittedinanyformforanyotherpurposewithoutpriorwrittenpermissionfromISO.

RequestsforpermissiontoreproducethisdocumentforthepurposeofsellingitshouldbeaddressedasshownbelowortoISO’smemberbodyinthecountryoftherequester:

ISOcopyrightoffice

Casepostale56,CH-1211Geneva20

Tel.+41227490111

Fax+41227490947

[email protected]

Webwww.iso.org

Reproductionforsalespurposesmaybesubjecttoroyaltypaymentsoralicensingagreement.

Violatorsmaybeprosecuted.

Page 3: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

BaselineEdition TR24772–3

©ISO/IEC2017–Allrightsreserved iii

Contents Page

Foreword...............................................................................................................................................v

Introduction..........................................................................................................................................vi

1.Scope..................................................................................................................................................1

2.Normativereferences.........................................................................................................................1

3.Termsanddefinitions,symbolsandconventions................................................................................13.1Termsanddefinitions.......................................................................................................................1

4.Languageconcepts.............................................................................................................................6

5.AvoidingprogramminglanguagevulnerabilitiesinC...........................................................................7

6.SpecificGuidanceforCVulnerabilities................................................................................................86.1General.............................................................................................................................................86.2Typesystem[IHN]............................................................................................................................86.3Bitrepresentations[STR]..................................................................................................................96.4Floating-pointarithmetic[PLF].......................................................................................................106.5Enumeratorissues[CCB].................................................................................................................106.6Conversionerrors[FLC]...................................................................................................................126.7Stringtermination[CJM].................................................................................................................146.8Bufferboundaryviolation[HCB].....................................................................................................156.9Uncheckedarrayindexing[XYZ]......................................................................................................166.10Uncheckedarraycopying[XYW]...................................................................................................176.11Pointertypeconversions[HFC].....................................................................................................186.12Pointerarithmetic[RVG]...............................................................................................................186.13NULLpointerdereference[XYH]...................................................................................................196.14Danglingreferencetoheap[XYK].................................................................................................206.15Arithmeticwrap-arounderror[FIF]...............................................................................................216.16Usingshiftoperationsformultiplicationanddivision[PIK]...........................................................226.17Choiceofclearnames[NAI]..........................................................................................................226.18Deadstore[WXQ].........................................................................................................................236.19Unusedvariable[YZS]...................................................................................................................246.20Identifiernamereuse[YOW]........................................................................................................246.21Namespaceissues[BJL].................................................................................................................256.22Initializationofvariables[LAV].....................................................................................................256.23Operatorprecedenceandassociativity[JCW]...............................................................................256.24Side-effectsandorderofevaluationofoperands[SAM]...............................................................266.25Likelyincorrectexpression[KOA]..................................................................................................276.26Deadanddeactivatedcode[XYQ].................................................................................................286.27Switchstatementsandstaticanalysis[CLL]...................................................................................286.28Demarcationofcontrolflow[EOJ]................................................................................................296.29Loopcontrolvariables[TEX].........................................................................................................306.30Off-by-oneerror[XZH]..................................................................................................................31

Deleted: 77

Deleted: 99

Deleted: 99

Deleted: 99

Deleted: 1010

Deleted: 1111

Deleted: 1212

Deleted: 1413

Deleted: 1615

Deleted: 1616

Deleted: 1817

Deleted: 1918

Deleted: 1918

Deleted: 2019

Deleted: 2119

Deleted: 2220

Deleted: 2321

Deleted: 2522

Deleted: 2523

Deleted: 2623

Deleted: 2624

Deleted: 2724

Deleted: 2725

Deleted: 2825

Deleted: 2825

Deleted: 2826

Deleted: 2926

Deleted: 3128

Deleted: 3128

Deleted: 3330

Deleted: 3431

Deleted: 3531

Page 4: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

iv ©ISO/IEC2017–Allrightsreserved

6.31Structuredprogramming[EWD]....................................................................................................326.32Passingparametersandreturnvalues[CSJ]..................................................................................336.33Danglingreferencestostackframes[DCM]...................................................................................346.34Subprogramsignaturemismatch[OTR].........................................................................................346.35Recursion[GDL]............................................................................................................................356.36Ignorederrorstatusandunhandledexceptions[OYB]..................................................................356.37Type-breakingreinterpretationofdata[AMV]..............................................................................366.38Deepvs.shallowcopying[YAN]....................................................................................................366.38.1Applicabilitytolanguage............................................................................................................366.39Memoryleak[XYL].......................................................................................................................376.40Templatesandgenerics[SYM]......................................................................................................376.41Inheritance[RIP]...........................................................................................................................376.42ViolationsoftheLiskovsubstitutionprincipleorthecontractmodel[BLP]..................................386.43Redispatching[PPH].....................................................................................................................386.44Polymorphicvariables[BKK].........................................................................................................386.45Extraintrinsics[LRM]....................................................................................................................386.46Argumentpassingtolibraryfunctions[TRJ]..................................................................................386.47Inter-languagecalling[DJS]...........................................................................................................396.48Dynamically-linkedcodeandself-modifyingcode[NYY]...............................................................396.49Librarysignature[NSQ].................................................................................................................406.50Unanticipatedexceptionsfromlibraryroutines[HJW]..................................................................406.51Pre-processordirectives[NMP].....................................................................................................406.52Suppressionoflanguage-definedrun-timechecking[MXB]..........................................................416.53Provisionofinherentlyunsafeoperations[SKL]............................................................................416.54Obscurelanguagefeatures[BRS]..................................................................................................426.55Unspecifiedbehaviour[BQF]........................................................................................................426.56Undefinedbehaviour[EWF]..........................................................................................................436.57Implementation–definedbehaviour[FAB]....................................................................................436.58Deprecatedlanguagefeatures[MEM]...........................................................................................446.59Concurrency–Activation[CGA]....................................................................................................446.60Concurrency–Directedtermination[CGT]....................................................................................456.61Concurrentdataaccess[CGX].......................................................................................................456.62Concurrency–Prematuretermination[CGS]................................................................................456.63Lockprotocolerrors[CGM]...........................................................................................................466.64UncontrolledFormatStrings[SHL]...............................................................................................46

7.LanguagespecificvulnerabilitiesforC..............................................................................................46

8.Implicationsforstandardization.......................................................................................................46

Bibliography.........................................................................................................................................49

Index 50

Deleted: 3532

Deleted: 3632

Deleted: 3734

Deleted: 3834

Deleted: 3835

Deleted: 3935

Deleted: 4036

Deleted: 4036

Deleted: 4036

Deleted: 4137

Deleted: 4137

Deleted: 4137

Deleted: 4137

Deleted: 4237

Deleted: 4238

Deleted: 4238

Deleted: 4238

Deleted: 4238

Deleted: 4339

Deleted: 4339

Deleted: 4440

Deleted: 4440

Deleted: 4541

Deleted: 4541

Deleted: 4641

Deleted: 4642

Deleted: 4742

Deleted: 4743

Deleted: 4844

Deleted: 4944

Deleted: 4944

Deleted: 4945

Deleted: 5045

Deleted: 5045

Deleted: 5046

Deleted: 5146

Deleted: 5146

Deleted: 5449

Deleted: 5651

Page 5: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

BaselineEdition TR24772–3

©ISO/IEC2017–Allrightsreserved v

Foreword

ISO(theInternationalOrganizationforStandardization)andIEC(theInternationalElectrotechnicalCommission)formthespecializedsystemforworldwidestandardization.NationalbodiesthataremembersofISOorIECparticipateinthedevelopmentofInternationalStandardsthroughtechnicalcommitteesestablishedbytherespectiveorganizationtodealwithparticularfieldsoftechnicalactivity.ISOandIECtechnicalcommitteescollaborateinfieldsofmutualinterest.Otherinternationalorganizations,governmentalandnon-governmental,inliaisonwithISOandIEC,alsotakepartinthework.Inthefieldofinformationtechnology,ISOandIEChaveestablishedajointtechnicalcommittee,ISO/IECJTC1.

InternationalStandardsaredraftedinaccordancewiththerulesgivenintheISO/IECDirectives,Part2.

ThemaintaskofthejointtechnicalcommitteeistoprepareInternationalStandards.DraftInternationalStandardsadoptedbythejointtechnicalcommitteearecirculatedtonationalbodiesforvoting.PublicationasanInternationalStandardrequiresapprovalbyatleast75%ofthenationalbodiescastingavote.

Inexceptionalcircumstances,whenthejointtechnicalcommitteehascollecteddataofadifferentkindfromthatwhichisnormallypublishedasanInternationalStandard(“stateoftheart”,forexample),itmaydecidetopublishaTechnicalReport.ATechnicalReportisentirelyinformativeinnatureandshallbesubjecttorevieweveryfiveyearsinthesamemannerasanInternationalStandard.

Attentionisdrawntothepossibilitythatsomeoftheelementsofthisdocumentmaybethesubjectofpatentrights.ISOandIECshallnotbeheldresponsibleforidentifyinganyorallsuchpatentrights.

ISO/IECTR24772,waspreparedbyJointTechnicalCommitteeISO/IECJTC1,Informationtechnology,SubcommitteeSC22,Programminglanguages,theirenvironmentsandsystemsoftwareinterfaces.

Page 6: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

vi ©ISO/IEC2017–Allrightsreserved

Introduction

ThisdocumentprovidesguidancefortheprogramminglanguageC,sothatapplicationdevelopersconsideringorusingCwillbebetterabletoavoidtheprogrammingconstructsthatleadtovulnerabilitiesandtheirattendantconsequences.Thisguidancecanalsobeusedbydeveloperstoselectsourcecodeevaluationtoolsthatcandiscoverandeliminatesuchconstructsintheirsoftware,orthedevelopersofsuchtools.

ThisdocumentisintendedtobeusedwithTR24772–1,whichdiscussesprogramminglanguagevulnerabilitiesinalanguageindependentfashion.

Itshouldbenotedthatthisdocumentisinherentlyincomplete.Itisnotpossibletoprovideacompletelistofprogramminglanguagevulnerabilitiesbecausenewweaknessesarediscoveredcontinually.Anysuchreportcanonlydescribethosethathavebeenfound,characterized,anddeterminedtohavesufficientprobabilityandconsequence.

Deleted: C

Deleted: insoftwarewrittenintheClanguage

Deleted: some

Deleted: thatcouldleadtovulnerabilitiesDeleted: ThisreportcanalsobeusedincomparisonwithcompanionTechnicalReportsandwiththelanguage-independentreport,TR24772–1,toselectaprogramminglanguagethatprovidestheappropriatelevelofconfidencethatanticipatedproblemscanbeavoided.

Page 7: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

TechnicalReport ISO/IECTR24772:2015(E)

©ISO/IEC2017–Allrightsreserved 1

InformationTechnology—ProgrammingLanguages—Guidancetoavoiding

vulnerabilitiesinprogramminglanguages—Vulnerabilitydescriptionsfor

theprogramminglanguageC

1.Scope

Thisdocumentspecifiessoftwareprogramminglanguagevulnerabilitiestobeavoidedinthedevelopmentofsystemswhereassuredbehaviourisrequiredforsecurity,safety,mission-criticalandbusiness-criticalsoftware.Ingeneral,thisguidanceisapplicabletothesoftwaredeveloped,reviewed,ormaintainedforanyapplication.

Thisdocumentdescribesthewaythatthevulnerabilitieslistedinthelanguage-independentTR24772–1aremanifestedoravoidedintheClanguage.

2.Normativereferences

Thefollowingreferenceddocumentsareindispensablefortheapplicationofthisdocument.Fordatedreferences,onlytheeditioncitedapplies.Forundatedreferences,thelatesteditionofthereferenceddocument(includinganyamendments)applies.

ISO/IEC9899:2011—ProgrammingLanguages—CISO/IECTR24731-1:2007—ExtensionstotheClibrary—Part1:Bounds-checkinginterfacesISO/IECTR24731-2:2010—ExtensionstotheClibrary—Part2:DynamicAllocationFunctionsISO/IEC9899:2011/Cor.1:2012—Programminglanguages—C

ISO/IEC9945:2009--InformationTechnology--PortableOperatingSystemInterface(POSIX)withTC1:2013

3.Termsanddefinitions,symbolsandconventions

3.1Termsanddefinitions

Forthepurposesofthisdocument,thetermsanddefinitionsgiveninISO/IEC2382,inTR24772–1,in9899:2011andthefollowingapply.Othertermsaredefinedwheretheyappearinitalictype.

Thefollowingtermsareinalphabeticalorder,withgeneraltopicsreferencingtherelevantspecificterms.

3.1.1

access:readormodifythevalueofanobject

Page 8: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

2 ©ISO/IEC2017–Allrightsreserved

Note:Modifyincludesthecasewherethenewvaluebeingstoredisthesameasthepreviousvalue.Expressionsthatarenotevaluateddonotaccessobjects

3.1.2

alignmentrequirementthatobjectsofaparticulartypebelocatedonstorageboundarieswithaddressesthatareparticularmultiplesofabyteaddress3.1.3

argument

expressioninthecomma-separatedlistboundedbytheparenthesesinafunctioncallexpression,orasequenceofpreprocessingtokensinthecomma-separatedlistboundedbytheparenthesesinafunction-likemacroinvocation

Note1:AlsocalledactualargumentNote2:Anargumentreplacesaformalparameterasthecallisrealized.

3.1.4

behaviourexternalappearanceoraction

Note:See:implementation-definedbehavior,locale-specificbehaviour,undefinedbehaviour,unspecifiedbehaviour

3.1.5

bitunitofdatastorageintheexecutionenvironmentlargeenoughtoholdanobjectthatmayhaveoneoftwovalues

Note:Itneednotbepossibletoexpresstheaddressofeachindividualbitofanobject

3.1.6

byteaddressableunitofdatastoragelargeenoughtoholdanymemberofthebasiccharactersetoftheexecutionenvironmentNote:Itispossibletoexpresstheaddressofeachindividualbyteofanobjectuniquely.Abyteiscomposedofacontiguoussequenceofbits,thenumberofwhichisimplementation-defined.Theleastsignificantbitiscalledthelow-orderbit;themostsignificantbitiscalledthehigh-orderbit.

Page 9: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 3

3.1.7

characterabstractmemberofasetofelementsusedfortheorganization,control,orrepresentationofdata

Note:See:single-bytecharacter,multibytecharacter,widecharacter

3.1.8

correctlyroundedresult:representationintheresultformatthatisnearestinvalue,subjecttothecurrentroundingmode,towhattheresultwouldbegivenunlimitedrangeandprecision3.1.9

diagnosticmessage:messagebelongingtoanimplementation-definedsubsetoftheimplementation’smessageoutput

Note:TheCStandardrequiresdiagnosticmessagesforallconstraintviolations.

3.1.10

formalparameter:objectdeclaredaspartofafunctiondeclarationordefinitionthatacquiresavalueonentrytothefunction,oranidentifierfromthecomma-separatedlistboundedbytheparenthesesimmediatelyfollowingthemacronameinafunction-likemacrodefinition3.1.11

implementation:particularsetofsoftware,runninginaparticulartranslationenvironmentunderparticularcontroloptions,thatperformstranslationofprogramsfor,andsupportsexecutionoffunctionsin,aparticularexecutionenvironment3.1.12

implementation-definedbehaviour: behaviourwheremultipleoptionsarepermittedbythestandardandwhereeachimplementationdocumentshowthechoiceismade

Note:Anexampleofimplementation-definedbehaviouristhepropagationofthehigh-orderbitwhenasignedintegerisshiftedright.

3.1.13

Formatted: Font:Bold

Formatted: Font:Bold

Formatted: Font:Bold

Formatted: Font:Bold

Formatted: Font:Bold

Deleted: unspecified

Page 10: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

4 ©ISO/IEC2017–Allrightsreserved

implementation-definedvalue:valuenotspecifiedinthestandardwhereeachimplementationdocumentshowthechoiceforthevalueisselected3.1.14

implementationlimit:restrictionimposedupontheprogrambytheimplementation3.1.15

indeterminatevalue:unspecifiedvalueoratraprepresentation3.1.16

locale-specificbehaviour:behaviourthatdependsonlocalconventionsofnationality,culture,andlanguagethateachimplementationdocuments

Note:Anexample,locale-specificbehaviouriswhethertheislower()functionreturnstrueforcharactersotherthanthe26lowercaseLatinletters

3.1.17

memorylocation: objectofscalar1type,oramaximalsequenceofadjacentbit-fieldsallhavingnonzerowidth3.1.18

multibytecharacter:sequenceofoneormorebytesrepresentingamemberoftheextendedcharactersetofeitherthesourceortheexecutionenvironment,wheretheextendedcharactersetisasupersetofthebasiccharacterset3.1.19

object:regionofdatastorageintheexecutionenvironment,thecontentsofwhichcanrepresentvalues3.1.20

1Integertypes,FloatingtypesandPointertypesarecollectivelycalledscalartypesintheCStandard

Formatted: Font:Bold

Deleted: unspecified

Formatted: Font:Bold

Formatted: Font:Bold

Formatted: Font:Bold

Formatted: Font:Bold

Deleted:

Deleted: Note:Abit-fieldandanadjacentnon-bit-fieldmemberareinseparatememorylocations.Thesameappliestotwobit-fields,ifoneisdeclaredinsideanestedstructuredeclarationandtheotherisnot,orifthetwoareseparatedbyazero-lengthbit-fielddeclaration,oriftheyareseparatedbyanon-bit-fieldmemberdeclaration.Itisnotsafetoconcurrentlyupdatetwobit-fieldsinthesamestructureifallmembersdeclaredbetweenthemarealsobit-fields,nomatterwhatthesizesofthoseinterveningbit-fieldshappentobe.Forexampleastructuredeclaredas ... [1]

Formatted: Font:Bold

Formatted: Font:Bold

Page 11: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 5

parameter:actualargument,argument,orformalparameter3.1.21

recommendedpractice:specificationthatisstronglyrecommendedasbeinginkeepingwiththeintentoftheCStandard,butthatmaybeimpracticalforsomeimplementations3.1.22

runtime-constraint:requirementonaprogramwhencallingalibraryfunction3.1.23

single-bytecharacter:bitrepresentationthatfitsinabyte3.1.24

traprepresentation:objectrepresentationthatneednotrepresentavalueoftheobjecttype3.1.25

undefinedbehaviour:useofanon-portableorerroneousprogramconstructoroferroneousdata,forwhichtheCstandardimposesnorequirements

Note:Undefinedbehaviourrangesfromignoringthesituationcompletelywithunpredictableresults,tobehavingduringtranslationorprogramexecutioninadocumentedmannercharacteristicoftheenvironment(withorwithouttheissuanceofadiagnosticmessage),toterminatingatranslationorexecution(withtheissuanceofadiagnosticmessage).Anexampleof,undefinedbehaviouristhebehaviouronintegeroverflow.

3.1.26

unspecifiedbehaviour:useofanunspecifiedvalue,orotherbehaviourwheretheCStandardprovidestwoormorepossibilitiesandimposesnofurtherrequirementsonwhichischoseninanyinstance

Note:Forexample,unspecifiedbehaviouristheorderinwhichtheargumentsofafunctionareevaluated.

Formatted: Font:Bold

Formatted: Font:Bold

Formatted: Font:Bold

Formatted: Font:Bold

Formatted: Font:Bold

Formatted: Font:Bold

Formatted: Font:Bold

Deleted: to

Page 12: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

6 ©ISO/IEC2017–Allrightsreserved

3.1.27

unspecifiedvalue:validvalueoftherelevanttypewheretheCStandardimposesnorequirementsonwhichvalueischoseninanyinstance

Note:Anunspecifiedvaluecannotbeatraprepresentation.3.1.28

value:meaningofthecontentsofanobjectwheninterpretedashavingaspecifictype

Note:Seeimplementation-definedvalue,indeterminatevalue,unspecifiedvalue,traprepresentation

3.1.29

widecharacter:bitrepresentationcapableofrepresentinganycharacterinthecurrentlocaleNote:TheCStandardusesthenamewchar_tforobjectsofthistype

4.Languageconcepts

TheCprogramminglanguagewasdevelopedintheearly1970’satBellLabs,insupportofthedevelopmentoftheUnixoperatingsystem.Itsfirstpublishedspecificationwasin1978inthebook“TheCprogramminglanguage”[15].ThefirstISOstandardforCwaspublishedin1990andupdatedin1999and2011.

Cisanimperativelanguagethatsupportsstructuredprogrammingandhasastatictypesystem.Ithasoftenbeendescribedasa‘high-levelassembler’,inthatthesemanticgapbetweenaprogramandtheexecutablecodeissmall(asinatraditionalassembler),buthavingtheadvantagesofahigh-levellanguage:machineindependenceandstructuredprogrammingcontrolconstructs.

Thesmallsemanticgapbetweenprogramandexecutablecodemeansthattheresultingexecutablesarecompactandfast,makingCapopularlanguagefordevelopingoperatingsystemsandembeddedapplications.Thereisadesiretomaintainthisadvantageofthelanguage.Consequentlyasthelanguagehasdevelopedthereisastrategyofavoidingtheadditionofoverheadsthatdonotdirectlycontributetothebehavioroftheapplicationandtomaintainbackwardscompatibility,asembeddedsystemsinparticularcanbeindevelopmentandmaintenanceforaverylongtime.Thisdocumentproposesrestrictionsthatshouldbeimposedondevelopmentinanenvironmentwhererun-timefailureisunacceptable.Somekeyfeaturesofthelanguageare:

Formatted: Font:Bold

Formatted: Font:Bold

Formatted: Font:Bold

Page 13: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 7

• DuetoCbeinga‘high-levelassembler’andhavingbeenaroundforlongerthanmostotherhigh-levellanguages,ithasbecomeacommonexchangeformatbetweenotherlanguages.Inparticular,manylanguagesimplementtheCfunctioncallingmodel(atleastasaselectableoption),sothatthirdpartylibrariescanbeusedinmanylanguageenvironments

• ChasaparticularlycloserelationshipwithC++.InitiallyC++wasastrictsupersetofC,withonlyoneexceptionofafeatureinCnotbeinginC++.Whilstovertheyearstherehasbeensomedivergence,therelationshipisstillclose

• AnunusualfeatureofCisthepreprocessor.Thisallowstextualmanipulationofthecodebeforethecompilerconsiderstheprogram.Itisusedto:allowchangestothecodetomatchspecificimplementationenvironments,implementin-linefunctionsandimplementcode‘short-cuts’byallowingcomponentstatementstobeconstructedthatwouldnotbesyntacticallylegalusingafunctiondefinition

• SinceC11,thelanguagehashadanativethreadingmodel.Previously,parallelismcouldonlybeachievedusingthird-partylibrariesnotincludedinthestandard

• Unlikesomeotherlanguages,Cusestheterms‘pointer’and‘reference’synonymously.Similarly,theterms‘passbyreference’,‘passbypointer’and‘passbyaddress’alsohavethesamemeaning

5.AvoidingprogramminglanguagevulnerabilitiesinCInadditiontothegenericprogrammingrulesfromTR24772-1clause5.4,additionalrulesfromthissectionapplyspecificallytotheCprogramminglanguage.Therecommendationsofthissectionarerestatementsofrecommendationsfromclause6ofthisdocument,butrepresentonesstatedfrequently,orthatareconsideredasparticularlynoteworthybytheauthors.Clause6ofthisdocumentcontainsthefullsetofrecommendations,aswellasexplanationsoftheproblemsthatledtotherecommendationsbeingmade.

Index Reference1 Useamacrotoensurethatthesizeofmemoryallocatedwithmallocmatchesthe

intendedtypeoftheobject

[HFC]

2 UseboundscheckinginterfacesfromAnnexKofC11[4]infavourofnon-boundscheckinginterfaces,suchasstrcpy_sinsteadofstrcpy.

[HCB]

3 UsecommonlyavailablefunctionssuchasthePOSIXfunctionshtonl(),htons(),ntohl()andntohs()toconvertfromhostbyteordertonetworkbyteorderandviceversa

[STR]

4 Performrangecheckingbeforecopyingmemory(usingmechanismssuchasmemcpyandmemmove),unlessitcanbeshownthatarangeerrorcannotoccur.Boundscheckingisnotperformedautomatically,butintheinterestofspeedandefficiency,rangecheckingonlyneedstobedonewhenitcannotbestaticallyshownthatanaccessoutsideofthearraycannotoccur.

[XYW]

5 Checkthatapointerisnotnullbeforedereferencing,unlessitcanbeshownstaticallythatthepointercannotbenull.

[XYH]

6 Afteracalltofree,setthepointertonulltopreventmultipledeallocationoruseofadanglingreferenceviathispointer,asillustratedinthefollowingcode:

free(ptr);ptr=NULL;

.

[XYK]

Deleted: f

Deleted: Everyguidanceprovidedinthissection,andinthecorrespondingPartsection,issupportedmaterialinClause6ofthisdocument,aswellasotherimportantrecommendations. ... [2]

Deleted: Makecastsexplicitinthereturnvalueofmalloc.

Deleted: Example:s=(structfoo*)malloc(sizeof(structfoo)); ... [3]

Comment [CP2]: Ifwewanttostickwithatop10–I’dsuggestchangingthisto‘heedandresolveallcompilerwarnings’

Deleted: is

Deleted: Setthepointertonulltopreventmultipledeallocationoruseofadanglingreferenceviathispointer

Page 14: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

8 ©ISO/IEC2017–Allrightsreserved

7 Donotreaduninitializedmemory,includingmemoryallocatedbyfunctionssuchasmalloc.

[LAV]

8 Checkthattheresultofanoperationonanunsignedintegervaluewillnotcausewrapping,unlessitcanbeshownthatwrappingcannotoccur.Anyofthefollowingoperatorshavethepotentialtowrap:

a+ba–ba*ba++++aa----aa+=ba-=ba*=ba<<ba<<=b-a

[FIF]

9 Checkthattheresultofanoperationonasignedintegervaluewillnotcauseanoverflow,unlessitcanbeshownthatoverflowcannotoccur.Anyofthefollowingoperatorshavethepotentialtooverflow,whichisundefinedbehaviorinC:

a+ba–ba*ba/ba%ba++++aa----aa+=ba-=ba*=ba/=ba%=ba<<ba<<=b-a

[FIF]

10 Ensurethatatypeconversionresultsinavaluethatcanberepresentedintheresultingtype.

[FLC]

6.SpecificGuidanceforCVulnerabilities

6.1General

ThisclausecontainsspecificadviceforCaboutthepossiblepresenceofvulnerabilitiesasdescribedinTR24772-1,andprovidesspecificguidanceonhowtoavoidtheminCcode.ThissectionmirrorsTR24772-1clause6inthatthevulnerability“TypeSystem[IHN]”isfoundin6.2ofTR24772–1,andCspecificguidanceisfoundinclause6.2andsubclausesinthisTR.

6.2Typesystem[IHN]

6.2.1ApplicabilitytolanguageCisastaticallytypedlanguage.InsomewaysCisbothstronglyandweaklytypedasitrequiresallvariablestobetyped,butsometimesallowsimplicitorautomaticconversionbetweentypes.Forexample,Ccanimplicitlyconvertalonginttoanintandpotentiallydiscardmanysignificantdigits.Notethatintegersizesareimplementationdefinedsothatinsomeimplementations,theconversionfromalonginttoanintwillnotdiscardanydigitssincetheyarethesamesize.Insomeimplementations,allintegertypescouldbeimplementedasthesamesize.Callowsimplicitconversionsasinthefollowingexample: short a = 1023; int b; b = a;

Ifanimplicitconversioncouldresultinalossofdatasuchasinaconversionfroma32-bitinttoa16-bitshortint: int a = 100000; short b; b = a;

Deleted: will

Deleted: can

Deleted: precision

Page 15: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 9

manycompilerswillissueawarningmessage.Chasasetofrulestodeterminehowconversionbetweendatatypeswilloccur.Forinstance,everyintegertypehasanintegerconversionrankthatdetermineshowconversionsareperformed.Therankingisbasedontheconceptthateachintegertypecontainsatleastasmanybitsasthetypesrankedbelowit.6.2.2Guidancetolanguageusers

• FollowtheadviceprovidedinTR24772-1subclause6.2.5.• Beawareoftherulesfortypingandconversionstoavoidvulnerabilities.• Donotcasttoaninappropriatetype.

6.3Bitrepresentations[STR]

6.3.1ApplicabilitytolanguageCsupportsavarietyofsizesforintegerssuchasshortint,int,longintandlonglongint.Eachmayeitherbesignedorunsigned.Calsosupportsavarietyofbitwiseoperatorsthatfacilitatebitmanipulations,suchasleftandrightshiftsandbitwise&and|.Somebitmanipulationscancauseunexpectedresultsthroughmiscalculatedshiftsorplatformdependentvariations.Forinstance,rightshiftingasignedintegerisimplementationdefinedinC,whileshiftingbyanamountgreaterthanorequaltothesizeofthedatatypeisundefinedbehaviour.Forinstance,onahostwhereanintisofsize32bits, unsigned int foo(const int k) { unsigned int i = 1; return i << k; }isundefinedforvaluesofkgreaterthanorequalto32.Thestoragerepresentationforinterfacingwithexternalconstructscanalsocauseunexpectedresults.Byteordersmaybeinlittle-endianorbig-endianformatandunknowinglyswitchingbetweenthetwocanunexpectedlyaltervalues.

6.3.2Guidancetolanguageusers

InadditiontothegeneraladviceofTR24772-1clause6.3.5:

• Onlyusebitwiseoperatorsonunsignedintegervaluesastheresultsofsomebitwiseoperationsonsignedintegersareimplementationdefinedorundefined

• Whereavailable,usefunctionssuchasthePOSIXstandardfunctionshtonl(),htons(),ntohl()andntohs()toconvertfromhostbyteordertonetworkbyteorderandviceversa.Thiswouldbeneededtointerfacebetweenani80x86architecture,wheretheLeastSignificantByteisfirst,andsomethingwithnetworkbyteorder,asusedontheInternet,wheretheMostSignificantByteisfirst.Usebitwiseoperationsonlyasalastresort.

Deleted: ... [4]

Deleted: make

Deleted: easyDeleted: operators

Deleted: TheseDeleted: orvulnerabilitiesDeleted: BitmanipulationsarenecessaryforsomeapplicationsandmaybeoneofthereasonsthataparticularapplicationwaswritteninC.AlthoughmanybitmanipulationscanberathersimpleinC,suchasmaskingoffthebottomthreebitsinaninteger,morecomplexmanipulationscancauseunexpectedresults.

Deleted:

Deleted:

Deleted: .

Deleted: withthe

Page 16: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

10 ©ISO/IEC2017–Allrightsreserved

• Incaseswherethereisapossibilitythatashiftisgreaterthanthesizeofthevariable,performacheckasthefollowingexampleshows,oramoduloreductionbeforetheshift:

unsigned int i; unsigned int k; unsigned int shifted_i; … if (k < sizeof(unsigned int)*CHAR_BIT) shifted_i = i << k; else // handle error condition

6.4Floating-pointarithmetic[PLF]

6.4.1ApplicabilitytolanguageCpermitsthefloating-pointdatatypesfloat,doubleandlongdouble.Duetotheapproximatenatureoffloating-pointrepresentations,theuseoffloating-pointdatatypesinsituationswhereequalityistobetestedorwhereroundingcouldaccumulateovermultipleiterationsmayleadtounexpectedresultsandpotentialvulnerabilities.

Aswithmostdatatypes,Cisflexibleinhowfloat,doubleandlongdoublecanbeused.Forinstance,Callowstheuseoffloating-pointtypestobeusedasloopcountersandinequalitystatements,eventhoughinmostcasesthesewillnothavetheexpectedbehaviour.Forexample

float x; for (x=0.0; x!=1.0; x+=0.00000001)

mayormaynotterminateafter10,000,000iterations.Therepresentationsusedforxandtheaccumulatedeffectofmanyiterationsmaycause xtonotbeidenticalto1.0causingthelooptocontinuetoiterateforever.

Similarly,theBooleantest

float x=1.336f; float y=2.672f; if (x == (y/2))

mayormaynotevaluatetotrue.Giventhatxandyareconstantvalues,itisexpectedthatconsistentresultswillbeachievedonthesameplatform.However,itisquestionablewhetherthelogicperformsasexpectedwhenafloatthatistwicethatofanotheristestedforequalitywhendividedby2asabove.

6.4.2GuidancetolanguageusersFollowthegeneraladviceofTR24772-1clause6.4.5:

6.5Enumeratorissues[CCB]

6.5.1Applicabilitytolanguage

TheenumtypeinCcomprisesasetofnamedintegerconstantvaluesasintheexample: enum abc {A,B,C,D,E,F,G,H} var_abc;

Deleted: the

Deleted: floatanddoubleDeleted: neededDeleted: couldDeleted: insomesituations

Deleted: .Eventhoughaloopmaybeexpectedtoonlyiterateafixednumberoftimes,dependingonthevaluescontainedinthefloating-pointtypeandontheloopcounterandterminationcondition,theloopcouldexecuteforever.Forinstanceiteratingatimesequenceusing10nanosecondsastheincrement:

Deleted: Thiscandependonthevaluesselectedduetothequirksoffloating-pointarithmetic.

Deleted: Inadditionto

Deleted: <#>Beawarethatimplicitcastsmaymaketheresultingtypeofanexpressionfloating-point. ... [5]

Page 17: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 11

ThevaluesofthemembersofabcwouldbeA=0,B=1,C=2,andsoon.Callowsexplicitvaluestobeassignedtotheenumerationtypemembers,sothatthatmemberisassignedtheindicatedvalueandthenextmemberwilltakethenextvalue(unlessalsoexplicitlyassignedavalue).Sothedeclaration: enum abc {A,B,C=6,D,E,F=7,G,H} var_abc;isequivalentto: enum abc {A=0, B=1, C=6, D=7, E=8, F=7, G=8, H=9} var_abc;

Notethatthishasgapsinthesequenceofvaluesandrepeatedvalues.Thereareanumberofissuesthatcanarisewithenumerationtypes:

• Ctreatsenumerationmembersidenticallytointegers.Soanenumerationmembercanbeusedinanintegerexpression(usingitsassociatedvalue)andanintegercanbeassignedtoanenumerationtypeobject,evenifthereisnomemberassociatedwiththatvalue.Thisbecomesanissueifanenumerationtypeobjectisusedtocontrolaswitchstatement.Usingtheexampleabove2,iftheswitchhaseightcasestatements,forcase A:tocase H:thentherearetwoscenarioswheretheswitchmaynotbehaveasexpected:

o theusermayexpectallpossiblevaluestobecovered.However,ifthecontrolexpressionisavariableassignedH+1,thenthecodewill‘fallthough’,withoutexecutinganyofthecasestatements

o theaboveissuecanbeaddressedbyprovidingadefaultclause.However,inthesafetydomain,itiscommonpracticetoprovideadefaultclauseevenifthecode(apparently)canonlyeverhaveenumerationmembervaluesforthecontrolexpression.Theargumentisthatthisprotectsagainstunexpectedcorruptionofthecontrolvariable,saybyabuffetoverrun.However,ifthecompileralsothinksthecontrolvaluecanonlyeverbeoneoftheenumerationmembers,itispermittedtooptimizeawaythedefaultclause,meaningthattheexpectedprotectionmaynotexist.

• Thecodemayinitiallyhavebeenwrittenusingthedefaultassignmentofvalues(0..Numberofmembers–1).Ifanarrayisdeclaredwithbounds[Last_member + 1].Thishasoneelementforeachenumerationtypemember.Ifmaintenanceofthecodethenoccursthatmodifiestheassignmentofvalues,twoissuescanarise:

o amembermaybecreatedthathasavaluegreaterthanLast_member‘s,sotherewillbeundefinedbehaviorifthismemberisusedtoindexthearray

o thevaluescoveredbythemodifiedenumerationtypemembers,maynotformacontinuoussequencefrom0toNumberofmembers–1,witheithergapsinthesequenceorrepeatedvalues.Ifthemembersareusedtoinitializeandaccessthearray,thensomemembersofthearraywillremainuninitializediftherearegaps.Ifsomefinalprocessingisperformedonthearray,usinganintegercountfrom0toNumberofmembers–1,againthereislikelytobeundefinedbehavior.Iftherearerepeatedvalues,theresultisunlikelytobethatexpected.

2 defaultinitialization.TheexamplewhereDandFbothequal7wouldcauseacompilererrorduetorepeatedcaseselector.

Page 18: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

12 ©ISO/IEC2017–Allrightsreserved

6.5.2GuidancetolanguageusersInadditiontothegeneraladviceofTR24772-1clause6.5.5:

• Enumerationtypedeclarationsshouldbeinoneofthefollowingthreeformats:o noexplicitvalues:

e.g. enum abc {A,B,C,D,E,F,G,H} var_abc;.o asingleexplicitvalueforthefirstmember:

e.g. enum abc {A=5,B,C,D,E,F,G,H} var_abc; o allvaluesexplicit:

e.g. enum abc { A=0, B=1, C=6, D=7, E=8, F=7, G=8, H=9} var_abc;

• Avoidusingloopsthatiterateoveranenumthathasrepresentationspecifiedfortheenums,unlessitcanbeguaranteedthattherearenogapsorrepetitionofrepresentationvalueswithintheenumdefinition.

• Useanenumeratedtypetoselectfromalimitedsetofchoicestomakepossibletheuseoftoolstodetectomissionsofpossiblevaluessuchasinswitchstatements.

• Ifa‘precautionary’defaultstatementisaddedtoswitchstatementcontrolledbyanenumerationtype,makethecontrollingobjectvolatile,sothecompilercannotoptimizeitaway(arguably,acompliantcompilershouldn’toptimizeitawayanyway,butanumberofexamplehavebeenfoundthatdo).

6.6Conversionerrors[FLC]

6.6.1Applicabilitytolanguage

Cpermitsimplicitconversions.Thatis,Cwillautomaticallyperformaconversionwithoutanexplicitcast.Forinstance,Callows inti; floatf=1.25f; i=f;Thisimplicitconversionwilldiscardthefractionalpartoffandsetito1.IfthevalueoffisgreaterthanINT_MAX,thentheassignmentofftoiwouldbeundefined.TherulesforimplicitconversionsinCaredefinedintheCstandard.Forinstance,integertypessmallerthanintarepromotedwhenanoperationisperformedonthem.IfallvaluesofBoolean,characterorintegertypecanberepresentedasanint,thevalueofthesmallertypeisconvertedtoanint;otherwise,itisconvertedtoanunsignedint.

Comment [SGM5]: Delete“anyway”,replace“example”with“them”

Page 19: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 13

Integerpromotionsareappliedaspartoftheusualarithmeticconversionstocertainargumentexpressions;operandsoftheunary+,-,and~operators,andoperandsoftheshiftoperators.Thefollowingcodefragmentshowstheapplicationofintegerpromotions: char c1, c2; c1 = c1 + c2;

Integerpromotionsrequirethepromotionofeachvariable(c1andc2)toint.Thetwointvaluesareaddedandthesumistruncatedtofitintothechartype.Integerpromotionsareperformedtoavoidarithmeticerrorsresultingfromtheoverflowofintermediatevalues.Forexample: signed char cresult, c1, c2, c3; c1 = 100; c2 = 3; c3 = 4; cresult = c1 * c2 / c3;

Inthisexample,thevalueofc1ismultipliedbyc2.Theproductofthesevaluesisthendividedbythevalueofc3(accordingtooperatorprecedencerules).Assumingthatsignedcharisrepresentedasan8-bitvalue,theproductofc1andc2(300)cannotberepresentedasasignedchar.However,becauseofintegerpromotions,c1,c2,andc3areeachconvertedtoint,andtheoverallexpressionissuccessfullyevaluated.Theresultingvalueistruncatedandstoredincresult.Becausethefinalresult(75)isintherangeofthesignedchartype,theconversionfromintbacktosignedchardoesnotresultinlostdata.Itispossiblethattheconversioncouldresultinalossofdatashouldthedatabelargerthanthestoragelocation.Alossofdata(truncation)canoccurwhenconvertingfromasignedtypetoanarrowersignedtype.Forexample,thefollowingcodecanresultintruncation: signed long int sl = LONG_MAX; signed char sc = (signed char)sl;

TheCstandarddefinesrulesforintegerpromotions,integerconversionrank,andtheusualarithmeticconversions.Theintentoftherulesistoensurethattheconversionsresultinconsistentnumericalvalues,andthatthesevaluesminimizesurprisesintherestofthecomputation.ArecentinnovationfromISO/IECTR24731-1[9]thathasbeenaddedtotheCstandard9899:2011[4]isthedefinitionofthersize_t type.Extremelylargeobjectsizesarefrequentlyasignthatanobject’ssizewascalculatedincorrectly.Forexample,negativenumbersappearasverylargepositivenumberswhenconvertedtoanunsignedtypelikesize_t.Also,someimplementationsdonotsupportobjectsaslargeasthemaximumvaluethatcanberepresentedbytypesize_t.Forthesereasons,itissometimesbeneficialtorestricttherangeofobjectsizestodetectprogrammingerrors.Forimplementationstargetingmachineswithlargeaddressspaces,itisrecommendedthatRSIZE_MAXbedefinedasthesmallerofthesizeofthelargestobjectsupportedor(SIZE_MAX >> 1),evenifthislimitissmallerthanthesizeofsomelegitimate,butverylarge,objects.ImplementationstargetingmachineswithsmalladdressspacesmaywishtodefineRSIZE_MAXasSIZE_MAX,whichmeansthatthereisnoobjectsizethatisconsideredaruntime-constraintviolation.

6.6.2GuidancetolanguageusersInadditiontothegeneraladviceofTR24772-1subclause6.6.5:

Deleted:

Deleted: size

Deleted: BDeleted: however,

Deleted: withlessprecision

Deleted: thesame

Page 20: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

14 ©ISO/IEC2017–Allrightsreserved

• Checkthevalueofalargertypebeforeconvertingittoasmallertypetoseeifthevalueinthelargertypeiswithintherangeofthesmallertype.Anyconversionfromatypewithlargerrangetoasmallerrangecouldresultinalossofdata.Insomeinstances,thislossisdesired.Suchcasesshouldbeexplicitlyacknowledgedincomments.Forexample,thefollowingcodecouldbeusedtocheckwhetheraconversionfromanunsignedintegertoanunsignedcharacterwillresultinalossofdata:

unsigned int i; unsigned char c; … if (i <= UCHAR_MAX) { // check against the maximum value // for an object of type unsigned char c = (unsigned char) i; } else { // handle error condition }

• Closeattentionshouldbegiventoallwarningmessagesissuedbythecompilerregardingmultiplecasts.MakingacastinCexplicitwillbothremovethewarningandacknowledgethatthechangeinisintended.

• Ifmixedtypesareusedinanexpression,ensurethateachconversionpreservesthevaluebeforebeingusedasanoperandinanotheroperationinthesameexpression.

• Whenconvertingbetweenwidecharacterandmulti-bytecharactersandstrings,alwaysusetheappropriateconversionfunctions(wctombandwcsrtombsorwcsrtombs_srespectively).Similarlyformulti-bytetowidecharactersandstringsusembrtowcandmbsrtowcsormbsrtowcs_s

6.7Stringtermination[CJM]

6.7.1Applicabilitytolanguage

AstringinCiscomposedofacontiguoussequenceofcharactersterminatedbyandincludinganullcharacter(abytewithallbitssetto0).ThereforestringsinCcannotcontainthenullcharacterexceptastheterminatingcharacter.Insertinganullcharacterinastringeitherthroughabugorthroughmaliciousactioncantruncateastringunexpectedly.Alternatively,notputtinganullcharacterterminatorinastringcancauseactionssuchasstringcopiestocontinuewellbeyondtheendoftheexpectedstring.Overflowingastringbufferthroughtheintentionallackofanullterminatingcharactercanbeusedtoexposeinformationortoexecutemaliciouscode.

6.7.2GuidancetolanguageusersInadditiontothegeneraladviceofTR24772-1subclause6.7.5:

• UsethesaferandmoresecurefunctionsforstringhandlingthataredefinedinnormativeAnnexK3fromISO/IEC9899:2011[4]ortheISOTR24731-2—PartII:Dynamicallocationfunctions.BothofthesedefinealternativestringhandlinglibraryfunctionstothecurrentStandardCLibrary.Thefunctionsverifythatreceivingbuffersarelargeenoughfortheresultingstringsbeingplacedinthemandensurethatresultingstringsarenullterminated.OneimplementationofthesefunctionshasbeenreleasedastheSafeCLibrary.

3 SeecommentscorrectuseofAnnexKfunctionsin6.8.1Bufferboundaryviolation[HCB]

Deleted: precisionDeleted: precisionDeleted: typeDeleted: potentiallyDeleted: ofprecisionDeleted: precision

Deleted: precisionDeleted: onpurpose

Page 21: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 15

6.8Bufferboundaryviolation[HCB]

6.8.1Applicabilitytolanguage

Abufferboundaryviolationconditionoccurswhenanarrayisindexedoutsideitsbounds,orpointerarithmeticresultsinanaccesstostoragethatoccursoutsidetheboundsoftheobjectaccessed.InC,thesubscriptoperator[]isdefinedsuchthatE1[E2]isidenticalto*(E1+E2)andtoE2[E1],sothatinallcasesthevalueinlocation(E1+E2)isreturned.Cdoesnotperformboundscheckingonarrays,sothefollowingcode: int foo(const int i) { int x[] = {0,0,0,0,0,0,0,0,0,0}; return x[i]; }

willreturnwhateverisinlocationx[i]evenif,iwereequalto-10or10(assumingeithersubscriptwasstillwithintheaddressspaceoftheprogram).Thiscouldbesensitiveinformationorevenareturnaddress,whichifalteredcouldchangetheprogramflow.Thefollowingcodeismoreappropriateandwouldnotviolatetheboundariesofthearrayx:

int foo( const int i) { int x[X_SIZE] = {0}; if ( (i < 0) || (i >= X_SIZE) ) { return ERROR_CODE; } else { return x[i]; } }

Abufferboundaryviolationmayalsooccurwhencopying,initializing,writingorreadingabufferifattentiontotheindexoraddressesusedarenottaken.Forexample,inthefollowingmoveoperationthereisabufferboundaryviolation:

char buffer_src[]={“abcdefg”}; char buffer_dest[5]={0}; strcpy(buffer_dest, buffer_src);

Thebuffer_srcislongerthanthebuffer_dest,andthecodedoesnotcheckforthisbeforetheactualcopyoperationisinvoked.Asaferwaytoaccomplishthiscopywouldbetousestrncpy,thatcanbelimitedtocopyamaximumnumberofcharacters:

char buffer_src[]={“abcdefg”]; char buffer_dest[5]={0}; strncpy(buffer_dest, buffer_src, sizeof(buffer_dest) -1); buffer_dest[sizeof(buffer_dest)-1] = 0;

thiswouldnotcauseabufferboundsviolation,however,becausethedestinationbufferissmallerthanthesourcebuffer,thedestinationbufferwillnowhold“abcd”.Notethatthefinalmemberofbuffer_dest isexplicitlyassignedtheterminatorvalue. strncpy doesnotautomaticallyterminatestringsiflongerthantheindicatednumberofcharacters,sothismanualassignmenttothelastcharacterofthedestinationbuffershouldalwaysbemade.

Deleted: (Deleted: (Deleted: )Deleted: (Deleted: )

Deleted: )

Comment [SGM6]: Whatdoesthatmean?

Deleted: eitherrepresentation,Deleted:

Deleted: bychangingthevalueofx[-10]orx[10],

Deleted: i

Deleted:

Deleted: t

Deleted:

Deleted: ,the5thelementofthearraywouldholdthenullcharacter

Formatted: Font:(Default) +Theme Body (Calibri), 11 ptFormatted: Font:11 ptFormatted: Font:(Default) +Theme Body (Calibri), 11 pt

Page 22: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

16 ©ISO/IEC2017–Allrightsreserved

AfurtheralternativeistousetheequivalentfunctionfromnormativeannexKofC11[4]‘Bounds-checkinginterfaces’:

char buffer_src[]={“abcdefg”]; char buffer_dest[5]={0}; if ( strcpy_s(buffer_dest, sizeof(buffer_dest), buffer_src) ) { /* Error Handler */ }

Ifthesourcestringincludingtheterminatorissmallerthantheindicateddestinationbuffersize,thenthesourcestringiscopiedtothedestinationbuffer.If,asintheexample,thesourcestringistoobig,thefirstelementofthedestinationstringisassigned0(i.e.thedestinationbecomesanemptystring).Notethatstrcpy_sandrelatedfunctionsreturn0onsuccessandanon-zerovalueonerrors.Whencallingthesefunction,theerrorvalueshouldalwaysbechecked.

6.8.2GuidancetolanguageusersInadditiontothegeneraladviceofTR24772-1subclause6.8.5:

• Validateallinputvalues.• Checkanyarrayindexbeforeuseifthereisapossibilitythevaluecouldbeoutsidetheboundsofthe

array.• Uselengthrestrictivefunctionssuchasstrncpy()insteadofstrcpy(),unlessitcanbeshownthe

destinationbufferisbigenough,andnotingtherequirementtoensuretodestinationstringisterminated.Alsonotethatthismayleadtotruncationofthesourcestring.

• Usestackguardingadd-onstodetectoverflowsofstackbuffers.• Donotusethedeprecatedfunctions,suchasgets().• UsethesaferandmoresecurefunctionsforstringhandlingfromthenormativeannexKofC11[4],

Bounds-checkinginterfaces,butalwayscheckeachcallforareturnederrorcondition.

6.9Uncheckedarrayindexing[XYZ]

6.9.1Applicabilitytolanguage

Cdoesnotperformboundscheckingonarrays,soalthougharraysmaybeaccessedoutsideoftheirbounds,thevaluereturnedisundefinedandinsomecasesmayresultinaprogramtermination.Forexample,inCthefollowingcodeisvalid,though,forexample,ifihasthevalue10,theresultisundefined: int foo(const int i) { int t; int x[] = {0,0,0,0,0}; t = x[i]; return t; }

Thevariabletwilllikelybeassignedwhateverisinthelocationpointedtobyx[10] (assumingthatx[10]isstillwithintheaddressspaceoftheprogram).

Deleted: orotherlanguagefeatures

Deleted: <#>Beawarethattheuseofallofthesemeasuresmaystillnotbeabletostopallbufferoverflowsfromhappening.However,theuseofthemcanmakeitmuchrarerforabufferoverflowtooccurandmuchhardertoexploitit.

Deleted: <#>Thefunctionsverifythatoutputbuffersarelargeenoughfortheintendedresultandreturnafailureindicatoriftheyarenot.Optionally,failingfunctionscallaruntime-constraint

handlertoreporttheerror.Dataisneverwrittenpasttheendofanarray.Allstringresultsarenullterminated.Inaddition,thesefunctionsarere-entrant:theyneverreturnpointerstostaticobjectsownedbythefunction.AnnexKalsocontainsfunctionsthataddressinsecuritieswiththeCinput-outputfacilities.

Page 23: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 17

6.9.2Guidancetolanguageusers

• Performrangecheckingbeforeaccessinganarray.Intheinterestofspeedandefficiency,rangecheckingonlyneedstobedonewhenitcannotbestaticallyshownthatanaccessoutsideofthearraycannotoccur.

• UsethesaferandmoresecurefunctionsforstringhandlingfromthenormativeannexKofC11[4],Bounds-checkinginterfaces4.Thesearealternativestringhandlinglibraryfunctions.Thefunctionsverifythatreceivingbuffersarelargeenoughfortheresultingstringsbeingplacedinthemandensurethatresultingstringsarenullterminated.

6.10Uncheckedarraycopying[XYW]

6.10.1Applicabilitytolanguage

Abufferoverflowoccurswhensomenumberofbytesiscopiedfromonebuffertoanotherandtheamountbeingcopiedisgreaterthanisallocatedforthedestinationbuffer.Intheinterestofeaseandefficiency,Clibraryfunctionssuchas memcpy(void * restrict s1, const void * restrict s2, size_t n)

and memmove(void *s1, const void *s2, size_t n)areusedtocopythecontentsfromoneareatoanother.memcpy()andmemmove()simplycopymemoryandnochecksaremadeastowhetherthedestinationareaislargeenoughtoaccommodatethenbytesofdatabeingcopied.Itisassumedthatthecallingroutinehasensuredthatadequatespacehasbeenprovidedinthedestination.Problemscanarisewhenthedestinationbufferistoosmalltoreceivetheamountofdatabeingcopiedoriftheindicesbeingusedforeitherthesourceordestinationarenottheintendedindices.Aseparateissueisthatmemcpyassumesthatthememoryblockspointedtobys1ands2arenon-overlapping.Ifthisassumptionisfalse,theprogram’sbehaviourisundefined.Thisrestrictiondoesnotapplytomemmove.

6.10.2Guidancetolanguageusers

• Performrangecheckingbeforecallingamemorycopyingfunctionsuchasmemcpy()andmemmove().Thesefunctionsdonotperformboundscheckingautomatically.Intheinterestofspeedandefficiency,rangecheckingonlyneedstobedonewhenitcannotbestaticallyshownthatanaccessoutsideofthearraycannotoccur.

• UsethesaferandmoresecurefunctionsforstringhandlingfromthenormativeannexKofC11[4],Bounds-checkinginterfaces5.

4 SeecommentscorrectuseofAnnexKfunctionsin6.8.1Bufferboundaryviolation[HCB]

5 SeecommentscorrectuseofAnnexKfunctionsin6.8.1Bufferboundaryviolation[HCB]

Deleted: sinceCdoesnotperformboundscheckingautomatically

Deleted: (orotherunitsofstorage)

Deleted: units

Page 24: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

18 ©ISO/IEC2017–Allrightsreserved

6.11Pointertypeconversions[HFC]

6.11.1Applicabilitytolanguage

Callowscastingthevalueofapointertoandfromanotherdatatype.Theseconversionscancauseunexpectedchangestopointervalues.

Ifapointeriscasttoadifferenttypeandthenpointerarithmeticapplied(includingarrayindexing)thenthememoryaccessedmaynotbethatintended.Inparticularcastingapointertoastructtoabasictype(likeint)andthenattemptingtoexaminethemembersofthestructbyincrementingthepointermaynotgivetheexpectedresultsbecauseofthepossiblepresenceofpaddingbytes.Theonesafepointerconversionisfromapointertosomeobjecttypetovoid*andthenbacktotheoriginalpointertype.Thestandardguaranteesthistorestoretheoriginalpointer.Onespecificrecommendationisthatamacroisusedtoensurethatwhenmallocisusedtoallocatespaceforanobjectorarrayofaparticulartype,theresultofmallociscasttotheappropriatepointertype.ThatisforanobjectoftypeT: #define makeObjectOfTypeT(T) (T*)malloc(sizeof(T))

orforanarrayofNelements: #define makeArrayOfTypeT(T, N) (T*)malloc(sizeof(T) * N)

6.11.2Guidancetolanguageusers

• FollowtheadviceprovidedbyTR24772-1clause6.11.5.• Maintainthesametypetoavoiderrorsintroducedthroughconversions.• Useamacrotocastthevaluereturnedbymalloctothecorrecttype• Heedcompilerwarningsthatareissuedforpointerconversioninstances.

6.12Pointerarithmetic[RVG]

6.12.1Applicabilitytolanguage

WhenperformingpointerarithmeticinC,thesizeofthevaluetoaddtoapointerisautomaticallyscaledtothesizeofthetypeofthepointed-toobject.Forinstance,whenaddingavaluetothebyteaddressofa4-byteinteger,thevalueisscaledbyafactor4andthenaddedtothepointer.TheeffectofthisscalingisthatifapointerPpointstothei-thelementofanarrayobject,then(P)+Nwillpointtothei+n-thelementofthearray.Failingtounderstandhowpointerarithmeticworkscanleadtomiscalculationsthatresultinseriouserrors,suchasbufferoverflows.

InC,arrayshaveastrongrelationshiptopointers.ThefollowingexamplewillillustratearithmeticinCinvolvingapointerandhowtheoperationisdonerelativetothesizeofthepointer'starget.Considerthefollowingcodesnippet: int buf[5]; int *buf_ptr = buf;

Deleted: PointersinCrefertoaspecifictype,suchasinteger.Ifsizeof(int)is4bytes,andptr isapointertointegersthatcontainsthevalue0x5000,thenptr++wouldmakeptrequalto0x5004.However,ifptrwereapointertochar,thenptr++wouldmakeptrequalto0x5001.Itisthedifferenceduetodatasizescoupledwithconversionsbetweenpointerdatatypesthatcauseunexpectedresultsandpotentialvulnerabilities.Duetoarithmeticoperations,pointersmaynotmaintaincorrectmemoryalignmentormayoperateuponthewrongmemoryaddresses.

Deleted: Inparticular,makecastsexplicitinthereturnvalueofmalloc ... [6]Comment [SGM7]: Inotherplaceswesay“InadditiontotheadviceprovidedbyTR24772-1clause6.11.5”followedbythebullets.

Deleted: AlwaysDeleted: anappropriateDeleted: Thedecisionmaybemadetoavoidallconversionssoanywarningsmustbeaddressed.Notethatcastingintoandoutofvoid * pointerswillmostlikelynotgenerateacompilerwarningasthisisvalidinC.

Page 25: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 19

wheretheaddressofbufis0x1234,aftertheassignmentbuf_ptrpointstobuf[0].Adding1tobuf_ptrwillresultinbuf_ptr == 0x1238onahostwhereanintis4bytes;buf_ptrwillthenpointtobuf[1].Notrealizingthataddressoperationswillbeintermsofthesizeoftheobjectbeingpointedtocanleadtoaddressmiscalculationsandundefinedbehaviour.Indexinganarrayisimplementedbypointerarithmetic,sothataccessinganarrayelementarray[n]createsapointerequivalenttoarray+nandaccessingthememoryatthataddress6.12.2Guidancetolanguageusers

• FollowtheadviceprovidedbyTR24772-1clause6.12.5.• Consideranoutrightbanonpointerarithmetic(otherthanbyuseoftheindexoperator)duetoitserror-

pronenature.• Verifythatallpointersareassignedavalidmemoryaddressforuse.

6.13NULLpointerdereference[XYH]

6.13.1ApplicabilitytolanguageCallowsmemorytobedynamicallyallocatedprimarilythroughtheuseofmalloc(),calloc(),andrealloc().Eachwillreturntheaddresstotheallocatedmemory.Duetoavarietyofsituations,thememoryallocationmaynotoccurasexpectedandanullpointerwillbereturned.Otheroperationsorfaultsinlogiccanresultinamemorypointerbeingsettonull.Usingthenullpointerasthoughitpointedtoavalidmemorylocationcausesundefinedbehaviour.Spacefor10000integerscanbedynamicallyallocatedinCinthefollowingway: int *ptr = malloc(10000*sizeof(int)); // allocate space for 10000 ints

malloc()willreturntheaddressofthememoryallocatedoranullpointerifinsufficientmemoryisavailablefortheallocation.ItisgoodpracticeaftertheattemptedallocationtocheckwhetherthememoryhasbeenallocatedviaaniftestagainstNULL: if (ptr != NULL) // check to see that the memory could be allocated

Memoryallocationsusuallysucceed,soneglectingthistestandusingthememorywillusuallywork.Thatiswhyneglectingthenulltestwillfrequentlygounnoticed.Anattackercanintentionallycreateasituationwherethememoryallocationwillfailleadingtoundefinedbehaviour.

6.13.2Guidancetolanguageusers

• FollowtheadviceprovidedbyTR24772-1clause6.13.5.• Createaspecificcheckthatapointerisnotnullbeforedereferencingit.Asthiscanbeexpensiveinsome

cases(suchasinaforloopthatperformsoperationsoneachelementofalargesegmentofmemory),judiciouscheckingofthevalueofthepointeratkeystrategicpointsinthecodeisrecommended.

Comment [SGM8]: Putincourierfont

Comment [SGM9]: Inotherplaceswesay“InadditiontotheadviceprovidedbyTR24772-1clause6.12.5”followedbythebullets.

Deleted: theDeleted: ofpointerarithmetic

Deleted: can

Deleted: asegmentationfaultandotherunanticipatedsituations

Formatted: Space After: 0 ptDeleted: ion

Deleted: asegmentationfault

Deleted: Faultsinlogiccancauseacodepaththatwilluseamemorypointerthatwasnotdynamicallyallocatedoraftermemoryhasbeendeallocatedandthepointerwassettonullasgoodpracticewouldindicate.

Comment [SGM10]: Inotherplaceswesay“InadditiontotheadviceprovidedbyTR24772-1clause6.13.5”followedbythebullets.

Page 26: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

20 ©ISO/IEC2017–Allrightsreserved

6.14Danglingreferencetoheap[XYK]

6.14.1Applicabilitytolanguage

Callowsmemorytobedynamicallyallocatedprimarilythroughtheuseofofmalloc(),calloc(),andrealloc(). Callowsaconsiderableamountoffreedominaccessingthedynamicmemory.Pointerstothedynamicmemorycanbecreatedtoperformoperationsonthememory.Oncethememoryisnolongerneeded,itcanbereleasedthroughtheuseoffree().However,freeingthememorydoesnotpreventtheattempteduseofthepointerstothememoryandissuescanariseifoperationsareperformedaftermemoryhasbeenfreed.Considerthefollowingsegmentofcode: int foo() { int *ptr = malloc (100*sizeof(int));/* allocate space for 100 integers */ if (ptr != NULL) { /* check to see that the memory could be allocated */ /* perform some operations on the dynamic memory */ free (ptr); /* memory is no longer needed, so free it */ /* program continues performing other operations */ ptr[0] = 10; /* ERROR – memory being used after released */ … } … }

TheuseofmemoryinCafterithasbeenfreedisundefinedbehaviour.Dependingontheexecutionpathtakenintheprogram,freedmemorymayhavebeenreallocatedviaanothercallofmalloc()orotherdynamicmemoryallocation.Ifthememoryhasnotbeenreallocated,useofthememorymaybeunnoticed.However,ifthememoryhasbeenreallocated,alteringofthedatacontainedinthememorywillalmostcertainlyresultindatacorruption.Determiningthatadanglingmemoryreferenceisthecauseofaproblemandlocatingitcanbedifficult.Settingandusinganotherpointertothesamesectionofdynamicallyallocatedmemorycanalsoleadtoundefinedbehaviour.Considerthefollowingsectionofcode: int foo() { int *ptr = malloc (100*sizeof(int));/* allocate space for 100 integers */ if (ptr != NULL) { /* check to see that the memory could be allocated */ int ptr2 = &ptr[10]; /* set ptr2 to point to the 10th element of the allocated memory */ … /* perform some operations on the memory */ free (ptr); /* memory is no longer needed */ ptr = NULL; /* set ptr to NULL to prevent ptr from being used again */ … /* program continues performing other operations */ ptr2[0] = 10; /* ERROR – memory is being used after it has been released via ptr2 */ …

Deleted: stillbefreeormay

Deleted: thatisusedisstillfree

Deleted: can

Deleted: ... [7]Deleted: memory

Page 27: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 21

} return (0); }

Dynamicmemorywasallocatedviaamalloc()andthenlaterinthecode,ptr2wasusedtopointtoanaddressinthedynamicallyallocatedmemory.Afterthememorywasfreedusingfree(ptr)andthegoodpracticeofsettingptrtoNULLwasfollowedtoavoidadanglingreferencebyptrlaterinthecode,adanglingreferencestillexistedusingptr2.6.14.2Guidancetolanguageusers

• FollowtheadviceprovidedbyTR24772-1clause6.14.2.• SetafreedpointertoNULLimmediatelyafterafree()call,asillustratedinthefollowingcode:

free (ptr); ptr = NULL;

• Donotcreateanduseadditionalpointerstodynamicallyallocatedmemory.

6.15Arithmeticwrap-arounderror[FIF]

6.15.1ApplicabilitytolanguageGiventhefixedsizeofintegerdatatypes,continuouslyaddingtoanunsignedintegereventuallyresultsinavaluethatcannotberepresented.ForCthisisdefinedto‘wraparound’,soaddingonetothemaximumpositivevalueresultsinzero.Thishappenswithoutanydetectionornotificationmechanism.Continuouslyaddingtoasignedintegeruntilitreachesavaluethatcannotberepresentedresultsinundefinedbehaviour.Similarly,repeatedlysubtractingfromanunsignedintegerleadstowraparound,orundefinedbehaviourforsignedintegers.Forexample,considerthefollowingcodeforashort intcontaining16bits: int foo( short int i ) { i++; return i; }

Callingfoowiththevalueof32767wouldcauseundefinedbehaviour,suchaswrappingto-32768,trapping,oranyotherbehaviour.Manipulatingavalueinthiswaycanresultinunexpectedresultssuchasoverflowingabuffer.Forunsignedintegers,thewraparoundbehaviouriswelldefined,andmaybewhattheprogrammerintended.However,theprogrammermayhaveexpectednormalarithmeticbehaviour,andbeenunawarethatthevaluewasgettingtoobigtorepresent.Asitsimpossibleforthecompilerorananalysistooltodeterminewhattheprogrammerintended,itisbettertowarnifwraparoundmayoccur.

Deleted:

Deleted: <#>Onlyreferencedynamicallyallocatedmemoryusingthepointerthatwasusedtoallocatethememory.

Deleted: oneDeleted: willcausetheDeleted: toDeleted: gofrom

Deleted: sibleDeleted: toDeleted: Cpermitst

Deleted: toDeleted: oneDeleted: eventuallywillcause

Comment [SGM11]: Itis

Page 28: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

22 ©ISO/IEC2017–Allrightsreserved

InC,bitshiftingbyavaluegreaterthanthesizeofthedatatypeorbyanegativenumberisundefinedbehaviourforbothsignedandunsignedintegers.Thefollowingcode,whereaintis16bits,wouldbeundefinedwhenj >= 16orjisnegative: int foo( int i, const int j ) { return i>>j; }

6.15.2Guidancetolanguageusers

• FollowtheadviceprovidedbyTR24772-1clause6.15.2.• Checkthattheresultofanoperationonanunsignedintegervaluewillnotcausewrapping,unlessitcan

beshownthatwrappingcannotoccur.Anyofthefollowingoperatorshavethepotentialtowrap:a+ba–ba*ba++++aa----aa+=ba-=ba*=ba<<ba<<=b-a

• Checkthattheresultofanoperationonasignedintegervaluewillnotcauseanoverflow,unlessitcanbeshownthatoverflowcannotoccur.Anyofthefollowingoperatorshavethepotentialtooverflow,whichisundefinedbehaviorinC:a+ba–ba*ba/ba%ba++++aa----aa+=ba-=ba*=ba/=ba%=ba<<ba<<=b-a

• Usedefensiveprogrammingtechniquestocheckwhetheranoperationwilloverfloworunderflowthereceivingdatatype.Thesetechniquescanbeomittedifitcanbeshownatcompiletimethatoverfloworunderflowisnotpossible.

• Thenumberofbitstobeshiftedbyashiftoperatorshouldliebetween1and(n-1),wherenisthesizeofthedatatype.

6.16Usingshiftoperationsformultiplicationanddivision[PIK]

6.16.1Applicabilitytolanguage

TheissuesforCarewelldefinedinTR24772-1clause6.16UsingShiftOperationsforMultiplicationandDivision

[PIK].Alsoseeclause6.15ArithmeticWrap-aroundError[FIF].

6.16.2Guidancetolanguageusers

TheguidanceforCusersiswelldefinedinTR24772-1clause6.16UsingShiftOperationsforMultiplicationand

Division[PIK].Alsosee,6.15ArithmeticWrap-aroundError[FIF].

6.17Choiceofclearnames[NAI]

6.17.1Applicabilitytolanguage

ThepossibleconfusionofnameswithtypographicallysimilarcharactersisnotspecifictoC,butCisaspronetoitasanyotherlanguage.Dependinguponthelocalcharacterset,avoidhavingnamesthatonlydifferbycharactersthatmaybeconfused,suchas‘O’and‘0’

Deleted: Cisoftenusedforbitmanipulation.PartofthisisduetothecapabilitiesinCtomaskbitsandshiftthem.AnotherpartisduetotherelativeclosenessChastoassemblyinstructions.Manipulatingbitsonasignedvaluecaninadvertentlychangethesignbitresultinginanumberpotentiallygoingfromapositivevaluetoanegativevalue. ... [8]Deleted: thatis

Deleted: Onlyconductbitmanipulationsonunsigneddatatypes.

Page 29: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 23

ForC,themaximumsignificantnamelengthisimplementationdefined.Ifaprogramincludesnamesthatarelongerthanthedefinedmaximum,thecompilerwilltruncatethemtothemaximum.So,iftwonamesinaprogramonlydifferincharactersafterthemaximum,theywillbetreatedasthesame.Forfunctionsthisisusuallydetectedbythecompilerasanattemptedredeclaration,butforvariablesdeclaredindifferentbutoverlappingscopesthismayleadtothewrongvariablebeingused,asin:

int long_name_ending in_A = … { int long_name_ending in_B = … /* Use of long_name_ending in_A here will actually use long_name_ending in_B */ }

6.17.2Guidancetolanguageusers

• FollowtheadviceprovidedbyTR24772-1clause6.17.2.• Usenamesthatareclearandnon-confusing.• Useconsistencyinchoosingnames.• Keepnamesshortandconciseinordertomakethecodeeasiertounderstand.• Donotdeclarenameslongerthanthemaximumdefinedbytheimplementation.• Choosenamesthatarerichinmeaning.• Donotusesnamesthatonlydifferbyamixtureofcaseorthepresenceorabsenceofanunderscore

character.• Avoiddifferentiatingthroughcharactersthatarecommonlyconfusedvisuallysuchas‘O’and‘0’,‘I’(lower

case‘L’),‘l’(capital‘I’)and‘1’,‘S’and‘5’,‘Z’and‘2’,and‘n’and‘h’.

6.18Deadstore[WXQ]

6.18.1Applicabilitytolanguage

BecauseCisanimperativelanguage,programsinCcancontaindeadstores(locationsthatarewrittenbutneversubsequentlyread,orover-writtenwithoutaninterveningread).Thiscanresultfromanerrorintheinitialdesignorimplementationofaprogram,orfromanincompleteorerroneousmodificationofanexistingprogram.However,itmayalsobeintendedbehaviour,forexamplewheninitializingasparsearray.Itmaybemoreefficienttocleartheentirearraytozero,thenassignthenon-zerovalues,sothepresenceofdeadstoresshouldberegardedasawarningofapossibleerror,ratherthananactualerror.

Astoreintoavolatile-qualifiedvariablegenerallyshouldnotbeconsideredadeadstorebecauseaccessingsuchavariablemaycauseadditionalsideeffects,suchasinput/output(memory-mappedI/O)orobservabilitybyadebuggeroranotherthreadofexecution.

6.18.2Guidancetolanguageusers• FollowtheadviceprovidedbyTR24772-1clause6.18.2.• Usecompilersandanalysistoolstoidentifydeadstoresintheprogram.• Declarevariablesasvolatilewhentheyareintentionaltargetsofastorewhosevaluedoesnotappearto

beused.

Deleted: Cissomewhatsusceptibletoerrorsresultingfromtheuseofsimilarlyappearingnames.Cdoesrequirethedeclarationofvariablesbeforetheyareused.However,Callowsscopingsothatavariablethatisnotdeclaredlocallymayberesolvedtosomeouterblockandahumanreviewermaynotnoticethatresolution.Variable

Deleted: specificDeleted: andsooneimplementationmayresolvenamestoonelengthwhereasanotherimplementationmayresolvenamestoanotherlengthresultinginunintendedbehaviour

Deleted: Aswiththegeneralcase,callstothewrongsubprogramorreferencestothewrongdataelement(whenmissedbyhumanreview)canresultinunintendedbehaviour.

Comment [SGM12]: Badadvice.Changetoadifferentcompiler(oradifferentversionofthesamecompiler)changesthemaximumlength.Themainpointistoensurethatnamesdiffernearthebeginningofthestrings.

Deleted: <#>Keepinmindthatcodewillbereusedandcombinedinwaysthattheoriginaldevelopersneverimagined.... [9]Deleted: <#>entiatenamesthroughonly

Deleted: <#>/

Deleted: <#>Developcodingguidelinestodefineacommoncodingstyleandtoavoidtheabovedangerouspractices.

Page 30: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

24 ©ISO/IEC2017–Allrightsreserved

6.19Unusedvariable[YZS]

6.19.1Applicabilitytolanguage

Variablesmaybedeclared,butneverusedwhenwritingcodeortheneedforavariablemaybeeliminatedinthecode,butthedeclarationmayremain.Mostcompilerswillreportthisasawarningandthewarningcanbeeasilyresolvedbyremovingtheunusedvariable.

6.19.2Guidancetolanguageusers

• FollowtheadviceprovidedbyTR24772-1clause6.19.2.• Resolveallcompilerwarningsforunusedvariables.Havinganunusedvariableincodeindicatesthat

eitherwarningswereturnedoffduringcompilationorwereignoredbythedeveloper.

6.20Identifiernamereuse[YOW]

6.20.1Applicabilitytolanguage

Callowsscopingsothatavariablethatisnotdeclaredlocallymayberesolvedtosomeouterblockandthatresolutionmaycausethevariabletooperateonanentityotherthantheoneintended.Inthefollowingexample,becausethevariablenamevar1wasreused,theprintedvalueofvar1maybeunexpected.

int var1; /* declaration in outer scope */ var1 = 10; { int var2; int var1; /* declaration in nested (inner) scope */ var2 = 5; var1 = 1; /* var1 in inner scope is 1 */ }

print (“var1=%d\n”, var1); /* will print “var1=10” as var1 refers */ /* to var1 in the outer scope */

Removingthedeclarationofvar2willresultinadiagnosticmessagebeinggeneratedmakingtheprogrammerawareofanundeclaredvariable.However,removingthedeclarationofvar1intheinnerblockwillnotresultinadiagnosticasvar1willberesolvedtothedeclarationintheouterblockandaprogrammermaintainingthecodecouldveryeasilymissthissubtlety.Theremovingofinnerblockvar1willresultintheprintingofvar1=1insteadofvar1=10. 6.20.2Guidancetolanguageusers

• FollowtheadviceprovidedbyTR24772-1clause6.20.2.

Deleted: ThisistrivialinCasonesimplyneedstoremovethedeclarationofthevariable.

Deleted: BDeleted: inthefollowingexample

Page 31: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 25

• Ensurethatadefinitionofanentitydoesnotoccurinascopewhereadifferententitywiththesamenameisaccessibleandcanbeusedinthesamecontext.Alanguage-specificprojectcodingconventioncanbeusedtoensurethatsucherrorsaredetectablewithstaticanalysis.

6.21Namespaceissues[BJL]

6.21.1Applicabilitytolanguage

DoesnotapplytoCbecauseCrequiresuniquenamesandhasasingleglobalnamespace.Adiagnosticmessageisrequiredforduplicatenamesinasinglecompilationunit.

6.22Initializationofvariables[LAV]

6.22.1Applicabilitytolanguage

Local,automaticvariablescanassumeunexpectedvaluesiftheyareusedbeforetheyareinitialized.TheCStandardspecifies,"Ifanobjectthathasautomaticstoragedurationisnotinitializedexplicitly,itsvalueisindeterminate".Inthecommoncase,onarchitecturesthatmakeuseofaprogramstack,thisvaluedefaultstowhichevervaluesarecurrentlystoredinstackmemory.Whileuninitializedmemorymaycontainzeros,thisisnotguaranteed.Consequently,uninitializedmemorycancauseaprogramtobehaveinanunpredictableorunplannedmannerandmayprovideanavenueforattack.

Manyimplementationswillissueadiagnosticmessageindicatingthatavariablehasbeenusedthatwasnotinitialized.

6.22.2Guidancetolanguageusers

• FollowtheadviceprovidedbyTR24772-1clause6.22.2.• Heedcompilerwarningmessagesaboutuninitializedvariables.Thesewarningsshouldberesolvedas

recommendedtoachieveacleancompileathighwarninglevels.• Donotusememoryallocatedbyfunctionssuchasmalloc()beforethememoryisinitializedasthe

memorycontentsareindeterminate.

6.23Operatorprecedenceandassociativity[JCW]

6.23.1Applicabilitytolanguage

OperatorprecedenceandassociativityinCareclearlydefined.

Mixedlogicaloperatorsareallowedwithoutparentheses.

6.23.2Guidancetolanguageusers

• FollowtheguidanceprovidedinTR24772-1clause6.23.5• Useparenthesesanytimearithmeticoperators,logicaloperators,andshiftoperatorsaremixedinan

expression,orwheretheexpressioniscomplexandmaybedifficulttoparseforreviewormaintenance.

Deleted: <#>Ensurethatadefinitionofanentitydoesnotoccurinascopewhereadifferententitywiththesamenameisaccessibleandhasatypethatpermitsittooccurinatleastonecontextwherethefirstentitycanoccur. ... [10]

Deleted: oftenDeleted: s

Deleted: Assumingthatanuninitializedvariableis0canleadtounpredictableprogrambehaviourwhenthevariableisinitializedtoavalueotherthan0.

Deleted: Formatted: Font:(Default) CalibriFormatted: List Paragraph, Bulleted + Level: 1 + Aligned at: 0.63 cm + Indent at: 1.27 cm

Comment [SGM13]: Iamunhappyaboutthisone.C’slargenumberofprecedencescauseconfusionfortheaverageprogrammer.Yes,theyareclearlydefined,buttheyarecomplex.

Page 32: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

26 ©ISO/IEC2017–Allrightsreserved

6.24Side-effectsandorderofevaluationofoperands[SAM]

6.24.1ApplicabilitytolanguageCallowsexpressionstohavesideeffects.Iftwoormoresideeffectsmodifythesameexpressionasin: int v[10]; int i; /* … */ i = v[i++];

thebehaviourisundefinedandthiscanleadtounexpectedresults.Eitherthe“i++”isperformedfirstortheassignmenti=v[i] isperformedfirst,orsomeotherunspecifiedbehaviouroccurs.Becausetheorderofevaluationcanhavedrasticeffectsonthefunctionalityofthecode,thiscangreatlyimpactportabilityandleadtounexpectedbehaviour.ThereareseveralsituationsinCwheretheorderofevaluationofsubexpressionsortheorderinwhichsideeffectstakeplaceisunspecifiedincluding:

• Theorderinwhichtheargumentstoafunctionareevaluated(C,Section6.5.2.2,"Functioncalls").• Theorderofevaluationoftheoperandsinanassignmentstatement(C,Section6.5.16,"Assignment

operators").• Theorderinwhichanysideeffectsoccuramongtheinitializationlistexpressionsisunspecified.In

particular,theevaluationorderneednotbethesameastheorderofsubobjectinitialization(C,Section6.7.9,“Initialization").

Becausetheseareunspecifiedbehaviours,testingmaygivethefalseimpressionthatthecodeisworkingandportable,whenitcouldjustbethatthevaluesprovidedcauseevaluationstobeperformedinaparticularorderthatcausessideeffectstooccurasexpected.Thereisalsoacommonmisconceptionthatbracketinginfluencestheorderofevaluation.Thisisnottrue.IfA,BandCarefunctionsthatreturnintegers,thenin: ( A() + B() ) * C()

thebracketsdon’taffecttheorderofevaluationofA,BandC,butdoaffecttheorderinwhichtheresultsofthesefunctionsarecombined.A,BandCmaybeevaluatedinanyorder,andiftheymodifycommonvariablestheresultisunspecified.6.24.2Guidancetolanguageusers

• FollowtheguidanceprovidedinTR24772-1clause6.24.5• ExpressionsshouldbewrittensothatthesameeffectswilloccurunderanyorderofevaluationthattheC

standardpermitssincesideeffectscanbedependentonanimplementationspecificorderofevaluation.• BecomefamiliarwithAnnexCoftheCstandardISO/IEC9899:2011[4],whichisalistofthesequence

pointsthatenforceanorderingofcomputations.

Deleted: undefined

Formatted: Font:(Default) Courier New

Deleted:

Page 33: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 27

6.25Likelyincorrectexpression[KOA]6.25.1ApplicabilitytolanguageChasseveralinstancesofoperatorswhicharesimilarinstructure,butvastlydifferentinmeaning,forexampleconfusingthecomparisonoperator“==”withassignment“=”.Usinganexpressionthatissyntacticallycorrect,butwhichmayjustbeanullstatementcanleadtounexpectedresults.Consider:

int x, y; /* … */ if (x = y){ /* … */ }

Afairamountofanalysismayneedtobedonetodeterminewhethertheprogrammerintendedtodoanassignmentaspartoftheifstatement(perfectlyvalidinC)orwhethertheprogrammermadethecommonmistakeofusingan“=”insteadofa“==”.Inordertopreventthisconfusion,itissuggestedthatanyassignmentsincontextsthatareeasilymisunderstoodbemovedoutsideoftheBooleanexpression.Thiswouldchangetheexamplecodetothesemanticallyequivalent:

int x,y; /* … */ x = y; if (x == 0) { /* … */ }

Thiswouldclearlystatewhattheprogrammermeantandthattheassignmentofytoxwasintended.Itisalsonotunknownforprogrammerstoinsertthe“;”statementterminatorprematurely.However,inadvertentlydoingthiscandrasticallyalterthemeaningofcode,eventhoughthecodeisvalid,asinthefollowingexample: int a,b; /* … */ if (a == b); // the semi-colon will make this a null statement { /* … */ }

Becauseofthemisplacedsemi-colon,thecodeblockfollowingtheifwillalwaysbeexecuted.Inthiscase,itisextremelylikelythattheprogrammerdidnotintendtoputthesemi-colonthere.6.25.2Guidancetolanguageusers

• FollowtheguidanceprovidedinTR24772-1clause6.25.5• Simplifystatementswithinterspersedcommentstoclarifyprogrammingfunctionalityandhelpfuture

maintainersunderstandtheintentandnuancesofthecode.• Avoidassignmentsembeddedwithinotherstatements,asthesecanbeproblematic.Eachofthe

followingwouldbeclearerandhavelesspotentialforproblemsiftheembeddedassignmentswereconductedoutsideoftheexpressions:

int a,b,c,d;

Deleted: .Thisisso

Deleted: commonthattheCexampleofconfusingtheBoolean

Deleted: operatorDeleted: theDeleted: isfrequentlycitedasanexampleamongprogramminglanguages

Deleted: technicallyDeleted: ... [11]Formatted: FrenchComment [SGM14]: Remove.“valid”isprecise.

Formatted: French

Deleted:

Deleted: PDeleted: caneasilyDeleted: getinthehabitof

Deleted: ingDeleted: attheendofstatements

Deleted: aidinaccurately

Deleted: TheflexibilityofCpermitsaprogrammertocreateextremelycomplexexpressions.

Page 34: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

28 ©ISO/IEC2017–Allrightsreserved

/* … */ if ((a == b) || (c = (d-1))) // the assignment to c may not // occur if a is equal to b

or: int a,b,c; /* … */ foo (a=b, c);

EachisavalidCstatement,buteachmayhaveunintendedresults.• Givenullstatementsasourcelineoftheirown.This,combinedwithenforcementbystaticanalysis,

wouldmakeclearertheintentionthatthestatementwasmeanttobeanullstatement.• Considertheadoptionofacodingstandardthatlimitstheuseoftheassignmentstatementwithinan

expression.6.26Deadanddeactivatedcode[XYQ]6.26.1ApplicabilitytolanguageCallowstheusualsourcesofdeadcode(describedin6.26ofTR24772-1)thatarecommontomostconventionalprogramminglanguages.Cusessomeoperatorsthatcanbeconfusedwithotheroperators.Forinstance,thecommonmistakeofusinganassignmentoperatorinaBooleantestasin:

int a; /* … */ if (a = 1) { … } else { … }

cancauseportionsofcodetobecomedeadcode,becausetheelseportionoftheifstatementcannotbereached.6.26.2Guidancetolanguageusers

• ApplytheguidanceprovidedinTR24772-1clause6.26.5.• Eliminatedeadcode.• Usecompilersandanalysistoolstoassistinidentifyingunreachablecode.• Use“//”commentsyntaxinsteadof“/*…*/”commentsyntaxtoavoidtheinadvertentcommentingout

sectionsofcode.

6.27Switchstatementsandstaticanalysis[CLL]6.27.1ApplicabilitytolanguageBecauseofthewayinwhichtheswitch-casestatementinCisstructured,itcanberelativelyeasytounintentionallyomitthebreakstatementbetweencasescausingunintendedexecutionofstatementsforsomecases.Ccontainsaswitchstatementoftheform:

Deleted: totheextentpossiblefromCprograms

Deleted: <#>Deletedeactivatedcodefromprogramsduetothepossibilityofaccidentallyactivatingit.

Page 35: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 29

char abc; /* … */ switch (abc) { case 1: sval = “a”; break; case 2: sval = “b”; break; case 3: sval = “c”; break; default: printf (“Invalid selection\n”); }

Ifthereisn’tadefaultcaseandtheswitchedexpressiondoesn’tmatchanyofthecases,thencontrolsimplyshiftstothenextstatementaftertheswitchstatementblock.Unintentionallyomittingabreakstatementbetweentwocaseswillcausesubsequentcasestobeexecuteduntilabreakortheendoftheswitchblockisreached.Thiscouldcauseunexpectedresults.6.27.2Guidancetolanguageusers

• ApplytheguidanceprovidedinTR24772-1subclause6.27.5• Onlyadirectfallthroughshouldbeallowedfromonecasetoanother.Thatis,everynonemptycase

statementshouldbeterminatedwithabreakstatementasillustratedinthefollowingexample:int i; /* … */ switch (i) { case 1: case 2: i++; /* fall through from case 1 to 2 is permitted */ break; case 3: j++; case 4: /* fall through from case 3 to 4 is not permitted */ /* as it is not a direct fall through due to the */ /* j++ statement */ }

• Ifdirectfallthroughfromonenonemptycasetoanotherisrequired,thenthisshouldbeclearlydocumentedbyacomment,preferablyonerecognizedbytheanalysistoolused.

• Adoptastylethatpermitsyourlanguageprocessorandanalysistoolstoverifythatallcasesarecovered.Wherethisisnotpossible,useadefaultclausethatdiagnosestheerror.

• Acodingstandardthatrequiresthedefaultclausetobeeitherthefirstorlastclauseintheswitchstatementcanassistthemaintenanceofcomplexswitchstatements

6.28Demarcationofcontrolflow[EOJ]

Deleted:

Page 36: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

30 ©ISO/IEC2017–Allrightsreserved

6.28.1ApplicabilitytolanguageClacksakeywordtobeusedasanexplicitterminator.Therefore,itmaynotbereadilyapparentwhichstatementsarepartofaloopconstructoranifstatement.Considerthefollowingsectionofcode:

int foo(int a, const int *b) { int i=0, count = 0; /* … */ a = 0; for (i=0; i<10; i++) a += b[i]; count++; printf(“%d %d\n”, a, count); }

Theprogrammermayhaveintendedbotha+=b[i];andcount++;tobethebodyoftheloop,butasthereisnoenclosingbrackets,thesecondstatementisonlyperformedonce.IfstatementsinCarealsosusceptibletocontrolflowproblemssincethereisn’tarequirementfortheretobeanelsestatementforeveryifstatement.AnelsestatementinCalwaysbelongtothemostrecentifstatementwithoutanelse.However,thesituationcouldoccurwhereitisnotreadilyapparenttowhichifstatementanelsebelongsduetothewaythecodeisindentedoraligned.6.28.2Guidancetolanguageusers

• FollowtherulesprovidedinTR24772-1clause6.28.5.• Enclosethebodiesofif,else,while,for,andsimilarinbraces.Thiswillreduceconfusionand

potentialproblemswhenmodifyingthesoftware.Forexample:int a,b,i; /* … */ if (i == 10){ a = 5; /* this is correct */ b = 10; }

else a = 10; b = 5;

Iftheassignmentstobwereaddedlaterandwereexpectedtobepartofeachifandelseclause(theyareindentedassuch),theabovecodeisincorrect:theassignmenttobthatwasintendedtobeintheelseclauseisunconditionallyexecuted.

6.29Loopcontrolvariables[TEX]6.29.1Applicabilitytolanguage

Deleted: ;

Deleted: {Atfirstitmayappearthatawillbeasumofthenumbersb[0]tob[9].However,eventhoughthecodeisarrangedsothatthea = a + b[i]codeappearstobewithintheforloop,the“;”attheendoftheforstatementcausesthelooptobeonanullstatement(the“;”)andthea = a + b[i];statementtoonlybeexecutedonce.Inthiscase,thismistakemaybereadilyapparentduringdevelopmentortesting.Moresubtlecasesmaynotbeasreadilyapparentleadingtounexpectedresults.

Deleted: Atfirstitmayappearthatawillbeasumofthenumbersb[0]tob[9].However,eventhoughthecodeisarrangedsothatthea = a + b[i]codeappearstobewithintheforloop,the“;”attheendoftheforstatementcausesthelooptobeonanullstatement(the“;”)andthea = a + b[i];statementtoonlybeexecutedonce.Inthiscase,thismistakemaybereadilyapparentduringdevelopmentortesting.Moresubtlecasesmaynotbeasreadilyapparentleadingtounexpectedresults.

Deleted: inC

Page 37: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 31

Callowsthemodificationofloopcontrolvariableswithintheloop,butcancauseunexpectedbehaviour.Sincethemodificationofaloopcontrolvariablewithinaloopisinfrequentlyencountered,reviewersofCcodemaynotexpectitandhencemissnoticingthemodificationornotrecognizeitssignificance.Modifyingtheloopcontrolvariablecancauseunexpectedresults,asin: int a,i; for (i=1; i<10; i++){ … if (a > 7) i = 10; … }

whichwouldcausetheforlooptoexitonceaisgreaterthan7regardlessofthenumberofiterationsthathaveoccurred.Cdoesn’trequiretheloopcontrolvariabletobeanintegertype.If,forexample,itisafloatingpointtype,thetestforcompletionshouldnotuseequalityorinequality,asfloatingpointroundingmayleadtomathematicallyinexactresults,andhenceanunterminatedloop.Thefollowingmaylooptentimesorindefinitely: float j; for (j = 0.0f; j != 10.0f; j += 1.0f){ … }

Thefollowingislittlebetter: float j; for (j = 0.0f; j < 10.0f; j += 1.0f){ … } Rounding may cause this loop to be performed ten or eleven times. To ensure this loop is performed ten times, j needs to be initialized to 0.5f.

6.29.2Guidancetolanguageusers

• ApplytheguidanceofTR24772-1clause6.29.5.• Donotmodifyaloopcontrolvariablewithinaloop.• Donotusefloatingpointtypesasaloopcontrolvariable

6.30Off-by-oneerror[XZH]6.30.1ApplicabilitytolanguageArraysareacommonplaceforoffbyoneerrorstomanifest.InC,arraysareindexedstartingat0,causingthecommonmistakeofloopingfrom0tothesizeofthearrayasin: int foo() { int a[10]; int i; for (i=0, i<=10, i++) …

Deleted: a

Deleted: .TDeleted: houghthisisusuallynotconsideredgoodprogrammingpracticeasit

Deleted: problems

Deleted: ,theflexibilityofCexpectstheprogrammertousethiscapabilityresponsibly

Deleted: ifnotcarefullydoneDeleted: .Deleted: InC,thefollowingisvalid

Deleted: .EventhoughthecapabilityexistsinC,itisstillconsideredtobeapoorprogrammingpractice.

Formatted: Indent: Left: 0 cm

Page 38: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

32 ©ISO/IEC2017–Allrightsreserved

return (0); }

StringsinCarealsoanothercommonsourceoferrorsinCduetotheneedtoallocatespaceforandaccountforthestringterminator.Acommonmistakeistoexpecttostoreannlengthstringinannlengtharrayinsteadoflengthn+1toaccountfortheterminating‘\0’.Interfacingwithotherlanguagesthatdonotuseterminatorsinstringscanalsoleadtoanoffbyoneerror.Cdoesnotflagaccessesoutsideofarraybounds,soanoffbyoneerrormaynotbedetectable.Severaltoolscanbeusedtohelpdetectaccessesbeyondtheboundsofarrays.However,suchtoolswillnothelpinthecasewhereonlyaportionofthearrayisusedandtheaccessisstillwithintheboundsofthearray.Loopingonemoreoronelessisusuallydetectablebygoodtesting.DuetothestructureoftheClanguage,thismaybethemainwaytoavoidthisvulnerability.Unfortunatelysomecasesmaystillslipthroughthedevelopmentandtestphaseandmanifestthemselvesduringoperationaluse.6.30.2Guidancetolanguageusers

• FollowtheguidanceofTR24772-1clause6.30.5.• Usecarefulprogramming,testingofboundaryconditionsandstaticanalysistoolstodetectoffbyone

errorsinC.

6.31Structuredprogramming[EWD]6.31.1ApplicabilitytolanguageItisaseasytowritestructuredprogramsinCasitisnotto.Ccontainsthegotoandlongjmpstatements,whichcancreateunstructuredcode.Calsohascontinue,break,andreturnthatcancreatecomplicatedcontrolflowwhenusedinanundisciplinedmanner.Unstructured{spaghetti}codecanbemoredifficultforCstaticanalyzerstoanalyzeandissometimesusedonpurposetoobfuscatethefunctionalityofsoftware.Codethathasbeenmodifiedmultipletimesbyanassortmentofprogrammerstoaddorremovefunctionalityortofixproblemscanbepronetobecomeunstructured.

BecauseunstructuredcodeinCcancauseproblemsforanalyzers(bothautomatedandhuman),problemswiththecodemaynotbedetectedasreadilyoratallaswouldbethecaseifthesoftwarewaswritteninastructuredmanner.

6.31.2Guidancetolanguageusers

• FollowtheguidanceofTR24772-1clause6.31.5.• Writeclearandconcisestructuredcodetomakecodeasunderstandableaspossible.

Restricttheuseofgoto,continue,breakandlongjmptoencouragemorestructuredprogramming.• IEC61508[12]highlyrecommendstheuseofnomorethanonereturnstatementinafunction.At

times,thisguidancecanhavetheoppositeeffect,suchasinthecaseofanifcheckofparametersatthestartofafunctionthatrequirestheremainderofthefunctiontobeencasedintheifstatementinordertoreachthesingleexitpoint.If,forexample,theuseofmultipleexitpointscanarguablymakeapieceof

Deleted: sentinelDeleted: valueDeleted: sentinelDeleted: sentinelDeleted: valuesDeleted: asDeleted: inCasinsomeotherlanguages

Deleted: goodandfreelyavailabletDeleted: forCDeleted: thatarecausedbyanoffbyoneerror

Deleted: border

Formatted: Font:(Default) Courier New, 10 ptFormatted: Font:10 ptDeleted: Also,Deleted: aDeleted: ,Deleted: intentionally

Deleted: ofcode

Formatted: Space After: 0 pt

Deleted: ,return

Formatted: Font:(Default) Courier New, 10 ptFormatted: Font:10 pt

Deleted: ... [12]

Page 39: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 33

codeclearer,thentheyshouldbeused.However,thecodeshouldbeabletowithstandacritiquethatarestructuringofthecodewouldhavemadetheneedformultipleexitpointsunnecessary.

6.32Passingparametersandreturnvalues[CSJ]6.32.1ApplicabilitytolanguageCusescallbyvalueparameterpassing.Theparameterisevaluatedanditsvalueisassignedtotheformalparameterofthefunctionthatisbeingcalled.Aformalparameterbehaveslikealocalvariableandcanbemodifiedinthefunctionwithoutaffectingtheactualargument.Anobjectcanbemodifiedinafunctionbypassingtheaddresstotheobjecttothefunction,forexample void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }Wherexandy areintegerpointerformalparameters,and*xand*y intheswap()functionbodydereferencethepointerstoaccesstheintegers.Ifitisnotintendedthatthefunctionshouldbeabletomodifytheobjectwhoseaddressispassedtothefunction,thepointershouldbemadeconstant,asconstint *p.Cmacrosuseacallbynameparameterpassing;acalltothemacroreplacesthemacrobythebodyofthemacro.Thisiscalledmacroexpansion.Macroexpansionisappliedtotheprogramsourcetextandamountstothesubstitutionoftheformalparameterswiththeactualparameterexpressions.Formalparametersareoftenparenthesizedtoavoidsyntaxissuesaftertheexpansion.Callbynameparameterpassingreevaluatestheactualparameterexpressioneachtimetheformalparameterisread.C11introducedtherestrictkeyword.Thismaybeappliedtofunctionpointerparameters.Whereafunctionhastwoormorepointerparametersmarkedwithrestrict,theprogrammeristellingthecompilerthatthefunctionwillneverbecalledwitharraysthathaveoverlappingaccess.Thisallowsthecompilertomakeuseofoptimizationsthatmayleadtoincorrectresultsifthearraysdooverlap,e.g.acopyfunctionlikestrncpythatcopiesafixednumberofcharactersfromasourcestringtoatarget.Ifthetargetoverlapsthesource,theresultdependsuponwhetherthecopyingwasperformedfromthestartofthestringtotheendorviceversa.Conversely,wherealibraryfunctionisdeclaredwithrestrictparameters,theprogrammerisbeingtoldnevertocallitsothataccesseswithinthefunctionoverlap.Thereisnocompileorrun-timecheckthattheparameterarraysareactuallynon-overlapping,socautionshouldbetakenwhenusingfunctionswithrestrictparameters.6.32.2Guidancetolanguageusers

• FollowtheguidanceofTR24772-1clause6.32.5.• Donotuseexpressionswithsideeffectsinparameterstofunction-likemacros,unlessitcanbeshown

thattheparameterisusedonlyonceinsidethemacro.• Donotuseexpressionswithsideeffectsformultipleparameterstofunctions,theorderinwhichthe

parametersareevaluatedandhencethesideeffectsoccurisunspecified.

Deleted:

Formatted: Font:(Default) Courier New, 10 ptFormatted: Font:10 ptFormatted: Font:(Default) Courier New, 10 pt

Deleted: accesses

Page 40: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

34 ©ISO/IEC2017–Allrightsreserved

• Usecautionwhenpassingtheaddressofanobject.Theobjectpassedcouldbeanalias6.AliasescanbeavoidedbyfollowingtherespectiveguidelinesofTR24772-1subclause6.32.5.

• Donotuseafunctionthatincludestherestrictkeywordunlessitcanbeestablishedthatthearrayparameterstothefunctioncanneveroverlap.

6.33Danglingreferencestostackframes[DCM]6.33.1ApplicabilitytolanguageCallowstheaddressofavariabletobestoredinapointervariable.Shouldthispointervariablepointto,forexample,theaddressofalocalvariablethatwaspartofastackframe,thenusingthisaddressafterthefunctioncontainingthelocalvariablehasterminatedleadstoundefinedbehaviour,asthememorywillhavebeenmadeavailableforfurtherallocationandmayindeedhavebeenallocatedforsomeotheruse.Thesameistrueforapointertomemoryallocatewithmallocetc.andwhichhassubsequentlybeenfreed.6.33.2Guidancetolanguageusers

• Donotassigntheaddressofanobjecttoanyentitywhichpersistsaftertheobjecthasceasedtoexist.Thisisdoneinordertoavoidthepossibilityofadanglingreference.Inparticular,neverreturntheaddressofalocalvariableastheresultofafunctioncall.

• Longlivedpointersthatcontainblock-localaddressesshouldbeassignedthenullpointervaluebeforeexecutingareturnfromtheblock.

6.34Subprogramsignaturemismatch[OTR]

6.34.1ApplicabilitytolanguageFunctionsinCmaybecalledwithmoreorlessthanthenumberofparametersthereceivingfunctionexpects.However,mostCcompilerswillgenerateawarningoranerroraboutthissituation.Ifthenumberofargumentsdoesnotequalthenumberofparameters,thebehaviourisundefined.Thiscanleadtounexpectedresultswhenthecountortypesoftheparametersdiffersfromthecallingtothereceivingfunction.Iftoofewargumentsaresenttoafunction,thenthefunctioncouldstillpoptheexpectednumberofargumentsfromthestackleadingtounexpectedresults.Callowsafunctiontotakeavariablenumberofarguments,asintheprintf()function.Thisisspecifiedinthefunctiondefinitionbyterminatingthelistofparameterswithanellipsis(...).Noinformationaboutthenumberortypesoftheparametersexpectedissupplied,andthecompilerwillacceptanynumberandtypeofparametersinthecall.

6Analiasisavariableorformalparameterthatreferstothesamelocationasanothervariableorformalparameter.

Deleted: s

Deleted: ’saddressbe

Deleted: e

Deleted: beendeallocatedDeleted: canyieldDeleted: expected

Formatted: Font:(Default) Courier New, 10 pt

Formatted: Font:10 ptDeleted: Anyuseofperishablememoryafterithasbeendeallocatedcanleadtounexpectedresults.

Deleted: Oncetheobjectceasestoexist,thensowillthestoredaddressoftheobjectpreventingaccidentaldanglingreferences.

Formatted: Highlight

Comment [CP15]: Idon’tbelievethishasbeentruesinceC90Ithinkweshoulddeletethis

Formatted: HighlightDeleted: infunctioncallsDeleted: .Deleted: Agoodexampleofanimplementationofthisisthe

Deleted: callDeleted: ,Deleted: Afterthecomma,

Deleted: nDeleted: Thiscanbeausefulfeatureforsituationssuchasprintf(),buttheuseofthisfeatureoutsideofspecialsituationscanbethebasisforvulnerabilities.

Page 41: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 35

Afunctiondefinitionmaybeforwardreferencedbyafunctiondeclaration,thatmayomittheparameterlist.Ifafunctionthatacceptsavariablenumberofargumentsisdefinedwithoutaparametertypelistthatendswiththeellipsisnotation,thebehaviourisundefined.Ccompilerswillattempttoperformanimplicitconversionfromthetypeofanactualparametertothetypeoftheformalparameter.Soforsqrt()thatisdefinedtoexpectadouble: double sqrt(double)

thecall: root2 = sqrt(2);

convertstheinteger2intothedoublevalue2.0.6.34.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.34.5.• Useafunctionprototypetodeclareafunctionwithitsexpectedparameterstoallowthecompilerto

checkforamatchingcountandtypesoftheparameters.• Donotusethevariableargumentfeatureexceptinrareinstances.Thevariableargumentfeature

suchasisusedinprintf()isdifficulttouseinatypesafemanner.6.35Recursion[GDL]6.35.1ApplicabilitytolanguageCpermitsrecursion,henceissubjecttotheproblemsdescribedinTR24772-1subclause6.35.6.35.2Guidancetolanguageusers

• ApplytheguidancedescribedinTR24772-1clause6.35.5.

6.36Ignorederrorstatusandunhandledexceptions[OYB]

6.36.1Applicabilitytolanguage

TheCstandarddoesnotincludeexceptionhandling,thereforeonlyerrorstatuswillbecovered.

Cprovidestheheaderfile<errno.h>thatdefinesthemacrosEDOM, EILSEQ and ERANGE,whichexpandtointegerconstantexpressionswithtypeint,distinctpositivevaluesandwhicharesuitableforusein#ifpreprocessingdirectives.Calsoprovidestheintegererrnothatmaybesettoanonzerovaluebyanylibraryfunctiontoindicatethatanerrorhasoccurred(iftheuseoferrnoisnotdocumentedinthedescriptionofthelibraryfunctionintheCStandard,errnocouldbeusedwhetherornotthereisanerror).Thoughthesevaluesaredefined,inconsistenciesinrespondingtoerrorconditionscanleadtovulnerabilities.errnoandthedefinedmacrosmayalsobeusedbyuserdefinedfunctions,butforclarity,suchuseshouldbeconsistentwiththeusebylibraryfunctions.

Deleted: F

Deleted: sDeleted: Deleted: orDeleted: notbedefinedwithafunctiondefinition.Thefunctiondefinitionmayormaynotcontainapara

Deleted: typeDeleted: Ifthecallingandreceivingfunctionsdifferinthetypeofparameters,

Deleted: will,ifpossible,doDeleted: suchasthecalltoDeleted: sDeleted: coerces

Formatted: List Paragraph, Bulleted + Level: 1 + Aligned at: 1.27 cm + Indent at: 1.9 cm

Deleted: include

Deleted: can

Formatted: Font:(Default) +Theme Body (Calibri)Formatted: Font:(Default) +Theme Body (Calibri), 14 ptFormatted: Font:(Default) +Theme Body (Calibri), 11 ptDeleted:

Formatted: Font:11 ptFormatted: Font:10 pt

Page 42: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

36 ©ISO/IEC2017–Allrightsreserved

Clibraryfunctionsmayalsoreturnerrorindicatorvalues.

6.36.2Guidancetolanguageusers

• Checkthereturnederrorstatusuponreturnfromafunction.• Seterrnotozerobeforealibraryfunctioncallinsituationswhereaprogramintendstocheckerrno

beforeasubsequentlibraryfunctioncall.• Useerrno_ttomakeitreadilyapparentthatafunctionisreturninganerrorcode.Oftenafunctionthat

returnsanerrnoerrorcodeisdeclaredasreturningavalueoftypeint.Althoughsyntacticallycorrect,itisnotapparentthatthereturncodeisanerrnoerrorcode.ThenormativeAnnexKfromISO/IEC9899:2011[4]introducesthenewtypeerrno_tin<errno.h>thatisdefinedtobetypeint.

• Handleanerrorascloseaspossibletotheoriginoftheerrorbutasfaroutasnecessarytobeabletodealwiththeerror.

• Whenafunctionreturnsanerrorvalue,otherthanusingerrno(e.g.mallocthatreturnsNULLiftherequestedmemoryallocationcannotbeperformed),alwayschecktheerrorconditionreturnedafteracall

• Foreachroutine,documentallerrorconditions,matchingerrordetectionandreportingneeds,andprovidesufficientinformationforhandlingtheerrorsituation.

• Usestaticanalysistoolstodetectandreportmissingorineffectiveerrordetectionorhandling.• Whenexecutionwithinaparticularcontextencountersanerror,finalizethecontextbyclosingopenfiles,

releasingresourcesandrestoringanyinvariantsassociatedwiththecontext.

6.37Type-breakingreinterpretationofdata[AMV]

6.37.1Applicabilitytolanguage

TheprimarywayinCthatareinterpretationofdatacanbeaccomplishedisthroughaunion,whichmaybeusedtointerpretthesamepieceofmemoryinmultipleways.Iftheuseoftheunionmembersisnotmanagedcarefully,thenunexpectedanderroneousresultsmayoccur.

6.37.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.37.5.• Whenusingunions,implementanexplicitdiscriminantandcheckitsvaluebeforeaccessingthedatain

theunion.

6.38Deepvs.shallowcopying[YAN]6.38.1Applicabilitytolanguage

Thisissuecanarisewhereastructorunioncontainsapointertoanobject.IfAandBaretwostructobjectsofthesametypethathasapointermember,thenthestatementA = B;copiesallthemembersofBtothe

Formatted: Font:11 pt

Formatted: Font:12 ptFormatted: NormalDeleted:

Deleted: TheCstandardlibraryfunctionsprovideanerrorstatusasthereturnvalueandsometimesinanadditionalglobalerrorvalue.

Formatted: Font:+Theme Body (Calibri)

Deleted: is

Deleted: Callowstheuseofpointerstomemorysothatanintegerpointercouldbeusedtomanipulatecharacterdata.Thiscouldleadtoamistakeinthelogicthatisusedtointerpretthedataleadingtounexpectedanderroneousresults.

Deleted: s

Page 43: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 37

equivalentmembersofA.Forthepointer,onlythepointeritselfhasbeencopied,soAandBbothnowpointtothesameobject,i.e.shallowcopying.

Iftherequiredbehavioristocopythestructandhaveeachcopypointtoitsownobject,thenafunctionisneededtoimplementdeepcopying,i.e.copyallthemembersofBtoA–otherthanthepointer,andallocatesufficientmemorytomakeacopyoftheobjectpointedtobyBandmakeApointtothisnewobject.

6.38.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.38.5.• Wherenecessary,createafunctiontocorrectlyperformthedeepcopy

6.39Memoryleak[XYL]

6.39.1Applicabilitytolanguage

Creliesontheprogrammertoimplementmemorymanagement,allocatingandfreeingdynamicmemoryasrequired,ratherthansupplyingabuiltingarbagecollector.

MemoryisdynamicallyallocatedinCusingthelibrarycallsmalloc(),calloc(),andrealloc().Whentheprogramnolongerneedsthedynamicallyallocatedmemory,itcanbereleasedusingthelibrarycallfree().Shouldtherebeaflawinthelogicoftheprogram,memorymaycontinuetobeallocatedbutnotfreedwhenitisnolongerneeded.Acommonsituationiswherememoryisallocatedwhileinafunction,thememoryisnotfreedbeforetheexitfromthefunctionandthelifetimeofthepointertothememoryhasendeduponexitfromthefunction.

6.39.2Guidancetolanguageusers

• Usedebuggingtoolssuchasleakdetectorstohelpidentifyunreachablememory.• Allocateandfreememoryinthesamemoduleandatthesamelevelofabstractiontomakeiteasierto

determinewhenandifanallocatedblockofmemoryhasbeenfreed.• Userealloc()onlytoresizedynamicallyallocatedarrays.• UsegarbagecollectorsthatareavailabletoreplacetheusualClibrarycallsfordynamicmemory

allocationwhichallocatememorytoallowmemorytoberecycledwhenitisnolongerreachable.Theuseofgarbagecollectorsmaynotbeacceptableforsomeapplicationsasthedelayintroducedwhentheallocatorreclaimsmemorymaybenoticeableorevenobjectionableleadingtoperformancedegradation.

6.40Templatesandgenerics[SYM]ThisvulnerabilitydoesnotapplytoC,becauseCdoesnotimplementthesemechanisms.6.41Inheritance[RIP]

Deleted: Ccanallowmemoryleaksasmanyprogramsusedynamicallyallocatedmemory.

Deleted: manual

Deleted: primarilysinceautomatedmemorymanagementcanbeunpredictable,impactperformanceandislimitedinitsabilitytodetectunusedmemorysuchasmemorythatisstillreferencedbyapointer,butisneverused

Formatted: Normal, No bullets or numberingDeleted: sDeleted: is

Page 44: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

38 ©ISO/IEC2017–Allrightsreserved

ThisvulnerabilitydoesnotapplytoC,becauseCdoesnotimplementstructhierarchies.6.42ViolationsoftheLiskovsubstitutionprincipleorthecontractmodel[BLP]ThisvulnerabilitydoesnotapplytoC,becauseCdoesnotimplementpolymorphism.

6.43Redispatching[PPH]ThisvulnerabilitydoesnotapplytoC,becauseCdoesnotimplementthismechanism.

6.44Polymorphicvariables[BKK]ThisvulnerabilitydoesnotapplytoC,becauseCdoesnotimplementthismechanism.6.45Extraintrinsics[LRM]ThisvulnerabilitydoesnotapplytoC,becauseCdoesnotimplementthesemechanisms.6.46Argumentpassingtolibraryfunctions[TRJ]

6.46.1Applicabilitytolanguage

ParameterpassinginCiseitherpassbyreferenceorpassbyvalue.Thereisn’taguaranteethatthevaluesbeingpassedwillbeverifiedbyeitherthecallingorreceivingfunctions.Sovaluesoutsideoftheassumedrangemaybereceivedbyafunctionresultinginapotentialvulnerability.

Aparametermaybereceivedbyafunctionthatwasassumedtobewithinaparticularrangeandthenanoperationorseriesofoperationsisperformedusingthevalueoftheparameterresultinginunanticipatedresultsandevenapotentialvulnerability.

6.46.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.46.5.• Donotmakeassumptionsaboutthevaluesofparameters.• Donotassumethatthecallingorreceivingfunctionwillberangecheckingaparameter.Therefore,

establishastrategyforeachinterfacetocheckparametersineitherthecallingorreceivingroutines.

Deleted: thismechanism

Page 45: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 39

6.47Inter-languagecalling[DJS]

6.47.1Applicabilitytolanguage

TheCStandarddefinesthecallingconventions,datalayout,errorhandingandreturnconventionsneededtouseCfromanotherlanguage.AdahasdevelopedastandardforinterfacingwithC.FortranhasincludedaClause15thatexplainshowtocallCfunctions.CallsfromCintootherlanguagesbecometheresponsibilityoftheprogrammer.

6.47.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.47.5.• Minimizetheuseofthoseissuesknowntobeerror-pronewheninterfacingfromC,suchas

1. passingcharacterstrings,2. dimension,boundsandlayoutissuesofarrays,3. interfacingwithotherparameterformatssuchascallbyreferenceorname,4. receivingreturncodes,and5. bitrepresentation.

6.48Dynamically-linkedcodeandself-modifyingcode[NYY]

6.48.1Applicabilitytolanguage

Mostloadersallowdynamicallylinkedlibrariesalsoknownassharedlibraries.Codeisdesignedandtestedusingasuiteofsharedlibrarieswhichareloadedatexecutiontime.TheprocessoflinkingandloadingisoutsidethescopeoftheCstandard.

Ccanallowself-modifyingcode.InCthereisn’tadistinctionbetweendataspaceandcodespace,executablecommandscanbealteredasdesiredduringtheexecutionoftheprogram.Althoughself-modifyingcodemaybeeasytodoinC,itcanbedifficulttounderstand,testandfixleadingtopotentialvulnerabilitiesinthecode.

Self-modifyingcodecanbedoneintentionallyinCtoobfuscatetheeffectofaprogramorinsomespecialsituationstoincreaseperformance.ModificationofCcodecanoccurifpointersaremisdirectedtoaccessthecodespaceinsteadofdataspaceorcodeisexecutedindataspace.Accidentalmodificationusuallyleadstoaprogramcrash.Intentionalmodificationcanalsoleadtoaprogramcrash,butusedinconjunctionwithothervulnerabilitiescanleadtomoreseriousproblemsthataffecttheentirehost.

6.48.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.48.5.• Donotuseself-modifyingcodeexceptinrareinstances.Inthoserareinstances,self-modifyingcodeinC

canandshouldbeconstrainedtoaparticularsectionofthecodeandwellcommented.• Verifythatthedynamicallylinkedorsharedcodebeingusedisthesameasthatwhichwastested.• Retestwhenitispossiblethatthedynamicallylinkedorsharedcodehaschangedbeforeusingthe

application.

Deleted: BecauseoftheeasewithwhichexecutablecodecanbemodifiedinC,accidental(ormaliciouslyintentional)

Deleted: mDeleted: modify

Deleted: Inthoseextremelyrareinstanceswhereitsuseisjustified,limittheamountofself-modifyingcodeandheavilydocumentit.

Page 46: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

40 ©ISO/IEC2017–Allrightsreserved

6.49Librarysignature[NSQ]

6.49.1ApplicabilitytolanguageIntegratingCandanotherlanguageintoasingleexecutablereliesonknowledgeofhowtointerfacethefunctioncalls,argumentlistsanddatastructuressothatsymbolsmatchintheobjectcodeduringlinking.Bytealignmentscanbeasourceofdatacorruption.

Forinstance,whencallingFortranfromC,severalissuesarise:• NeitherCnorFortrancheckformismatchargumenttypesoreventhenumberofarguments.• CpassesargumentsbyvalueandFortranpassesargumentsbyreference,soaddressesmustbepassedto

Fortranratherthanvaluesintheargumentlist.• MultidimensionalarraysinCarestoredinrowmajororder,whereasFortranstoresthemincolumnmajor

order.• StringsinCareterminatedbyanullcharacter,whereasFortranusesthedeclaredlengthofastring.

ThesearejustsomeoftheissuesthatarisewhencallingFortranprogramsfromC.EachlanguagehasitsdifferenceswithC,sodifferentissuesarisewitheachinterface.Writingalibrarywrapperisthetraditionalwayofinterfacingwithcodefromanotherlanguage.However,thiscanbequitetediousanderror-prone.

6.49.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.49.5.• Useatool,ifpossible,toautomaticallycreateinterfacewrappers.

6.50Unanticipatedexceptionsfromlibraryroutines[HJW]

SinceCdoesnothaveexceptionsandsocannothandleexceptionspassedfromotherlanguagesystems,thisvulnerabilitydoesnotapply.See6.36foradiscussionofIgnorederrors.SeeTR24772-1clause6.46inthecasewherelibrarieswritteninlanguagesthatuseexceptionsmaybecalled.

6.51Pre-processordirectives[NMP]

6.51.1ApplicabilitytolanguageTheCpre-processorallowstheuseofmacrosthataretext-replacedbeforecompilation.Function-likemacroslooksimilartofunctionsbuthavedifferentsemantics.Becausetheargumentsaretext-replaced,expressionspassedtoafunction-likemacromaybeevaluatedmultipletimes.Thiscanresultinunintendedandunspecifiedbehaviour,iftheargumentshavesideeffectsorarepre-processordirectivesasdescribedbyC§6.10[1].Additionally,theargumentsandbodyoffunction-likemacrosshouldbefullyparenthesizedtoavoidunintendedandunspecifiedbehaviour[2].Thefollowingcodeexampledemonstratesunspecifiedbehaviourwhenafunction-likemacroiscalledwith

Formatted: Space After: 0 pt

Deleted: .

Deleted:

Formatted: Space After: 0 pt

Deleted: <#>Usesignaturestoverifythatthesharedlibrariesusedareidenticaltothelibrarieswithwhichthecodewastested.

Deleted: <#>the

Deleted: nordoesit

Comment [SGM16]: Iamunhappywiththis.Thevulnerabilityexists.Theguidanceshouldbetoidentifywhattheexceptionmechanismisandexplicitlyprogramanerrorfunctiontoperformlastwishes.

Deleted: undefined

Deleted: undefined

Deleted: undefined

Page 47: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 41

argumentsthathaveside-effects(inthiscase,theincrementoperator)[2]:#define foo(X) ((X) * (X) + (X)) /* ... */ int i = 2; int a = foo(++i);

Theaboveexamplecouldexpandto: int a = ((++i) * (++i) + (++i));

thishasunspecifiedbehaviour,asitsnotknowninwhichorderthecompilerwillevaluatethethree++isubexpressions.Anothermechanismoffailurecanoccurwhentheargumentswithinthebodyofafunction-likemacroarenotfullyparenthesized.Thefollowingexampleshowsamacrowithoutparenthesizedarguments[2]:

#define CUBE(X) (X * X * X) /* ... */ int a = CUBE(2 + 1);

Thisexampleexpandsto: int a = (2 + 1 * 2 + 1 * 2 + 1)

whichevaluatesto7insteadoftheintended27.

6.51.2GuidancetolanguageusersThisvulnerabilitycanbeavoidedormitigatedinCinthefollowingways:

• FollowtheguidelinesofTR24772-1clause6.51.5.• Replacemacro-likefunctionswithinlinefunctionswherepossible.Althoughmakingafunctioninlineonly

suggeststothecompilerthatthecallstothefunctionbeasfastaspossible,theextenttowhichthisisdoneisimplementation-defined.Inlinefunctionsdoofferconsistentsemanticsandallowforbetteranalysisbystaticanalysistools.

• Ensurethatifafunction-likemacromustbeused,thatitsargumentsandbodyareparenthesized.• Donotusepre-processordirectivesorexpressionswithside-effects(suchasassignment,

increment/decrement,volatileaccess,orfunctioncalls)intheparameterofafunction-likemacro.6.52Suppressionoflanguage-definedrun-timechecking[MXB]

DoesnotapplytoCsincetherearenolanguage-definedruntimechecks.6.53Provisionofinherentlyunsafeoperations[SKL]

6.53.1ApplicabilitytolanguageCwasdesignedforimplementingsystemsoftwarewheresome‘unsafe’operationsareinherentandcommon.

Formatted: English (UK)Deleted: CUBE

Deleted: *

Deleted: 81 / CUBE

Deleted: 81 /

Deleted: *

Deleted: iDeleted: undefinedDeleted: sothismacroexpansionisdifficulttopredict

Formatted: Font:(Default) Courier New, 10 ptFormatted: Font:10 ptDeleted: theDeleted: CUBE

Formatted: English (UK)

Deleted: embed

Deleted: an

Deleted: aDeleted:

Comment [SGM17]: HowdoweresolvethiswiththeadviceforusingtheannexKfunctionsandstringhandlingboundsbydefiningmacros?

Page 48: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

42 ©ISO/IEC2017–Allrightsreserved

6.53.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.53.5.

6.54Obscurelanguagefeatures[BRS]

6.54.1Applicabilityoflanguage

Cisarelativelysmalllanguagewithalimitedsyntaxset,lackingmanyofthecomplexfeaturesofsomeotherlanguages.ManyofthecomplexfeaturesinCarenotimplementedaspartofthelanguagesyntax,butratherimplementedaslibraryroutines.Assuch,mostoftheavailablefeaturesinCareusedrelativelyfrequently.

Problemsaremorelikelytoarisefromtheuseofacombinationoffeaturesthatarerarelyusedtogetherorfraughtwithissuesifnotusedcorrectly.Thiscancauseunexpectedresultsandpotentialvulnerabilities.

6.54.2Guidancetolanguageusers

• ConsidertheguidelinesinTR24772-1clause6.54.5.• Organizationsshouldspecifycodingstandardsthatrestrictorbantheuseoffeaturesorcombinationsof

featuresthathavebeenobservedtoleadtovulnerabilitiesintheoperationalenvironmentforwhichthesoftwareisintended.

6.55Unspecifiedbehaviour[BQF]

6.55.1ApplicabilityoflanguageTheCstandardhasdocumented,inAnnexJ.1,54instancesofunspecifiedbehaviour.Examplesofunspecifiedbehaviourare:

• Theorderinwhichparametersofafunctioncallareevaluated• Theorderinwhichanysideeffectsoccuramongtheinitializationlistexpressionsinaninitializer• Thelayoutofstorageforfunctionparameters

Relianceonaparticularobservedbehaviourthatisunspecifiednotonlyleadstoportabilityproblemswhenthesamecodeiscompiledwithadifferentcompiler,butisnotrequiredtobeconsistentwithinthesameprogram.Manycasesofunspecifiedbehaviourhavetodowiththeorderofevaluationofsubexpressionsandsideeffects.Forexample,inthefunctioncall f1(f2(x), f3(x));

thefunctionsf2andf3maybecalledinanyorder,possiblyyieldingdifferentresults.

6.55.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.55.5.• Donotrelyonunspecifiedbehaviourbecausethebehaviourcanchangeateachinstance.Anycodethat

makesassumptionsaboutthebehaviourofsomethingthatisunspecifiedshouldbereplaced.

Deleted:

Deleted: Commonuseacrossavarietyoflanguagesmaymakesomefeatureslessobscure.Becauseoftheunstructuredcodethatisfrequentlytheresultofusinggoto’s,thegotostatementisfrequentlyrestricted,orevenoutrightbanned,insomeCdevelopmentenvironments.Eventhoughthegotoisencounteredinfrequentlyandtheuseofitconsideredobscure,becauseitisfairlyobviousastoitspurposeandsinceitsuseiscommontomanyotherlanguages,thefunctionalityofitiseasilyunderstoodbyeventhemostjuniorofprogrammers.

Deleted: TDeleted: addsyetanotherdimension.ParticularcombinationsoffeaturesinCmaybeused

Deleted: Deleted: incombination

Deleted: (Deleted: )S

Deleted: theoperandsofanassignmentoperator

Deleted: leads

Deleted: becausetheexpectedbehaviourmaybedifferentforanygiveninstance

Deleted: dependingontheorderinwhichthefunctionsarecalled

Deleted: Thus,a

Deleted: tomakeitlessreliantonaparticularinstallationandmoreportable

Page 49: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 43

6.56Undefinedbehaviour[EWF]

6.56.1ApplicabilitytolanguageTheCstandarddoesnotimposeanyrequirementsoncodewithundefinedbehaviour.Typicalundefinedbehavioursincludedoingnothing,producingarbitraryresults,andterminatingtheprogram.TheCstandardhasdocumented,inAnnexJ.2,191instancesofundefinedbehaviourthatexistinC.Oneexampleofundefinedbehaviouroccurswhenthevalueofthesecondoperandofthe/or%operatoriszero.Thisisgenerallynotdetectablethroughstaticanalysisofthecode,butcouldeasilybepreventedbyacheckforazerodivisorbeforetheoperationisperformed.Leavingthisbehaviourasundefinedlessenstheburdenontheimplementationofthedivisionandmodulooperators.Otherexamplesofundefinedbehaviourare:

• Referringtoanobjectoutsideofitslifetime• Theconversiontoorfromanintegertypethatproducesavalueoutsideoftherangethatcanbe

represented• Theuseoftwoidentifiersthatdifferonlyinnon-significantcharacters

Relyingonundefinedbehaviourmakesaprogramunstableandnon-portable.Whilesomecasesofundefinedbehaviourmaybehaveconsistentlyacrossmultipleimplementations,itisstilldangeroustorelyonthem.Relyingonundefinedbehaviourcanresultinerrorsthataredifficulttolocateandonlypresentthemselvesunderspecificcircumstances.Forexample,accessingmemoryafterithasbeendeallocatedbyfree()orrealloc()resultsinundefinedbehaviour,butitmayworkmostofthetime.

6.56.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.56.5.

6.57Implementation–definedbehaviour[FAB]

6.57.1ApplicabilitytolanguageTheCstandardhasdocumented,inAnnexJ.3,112instancesofimplementation-definedbehaviour.Examplesofimplementation-definedbehaviourare:

• Thenumberofbitsinabyte• Thedirectionofroundingwhenafloating-pointnumberisconvertedtoanarrowerfloating-pointnumber• Therulesforcomposingvalidfilenames

Relyingonimplementation-definedbehaviourcanmakeaprogramlessportableacrossimplementations.However,thisislesstruethanforunspecifiedandundefinedbehaviour.Also,asmanybasicproperties,suchasthesizesofthebasictypes,areimplementationdefined,itisvirtuallyimpossibletoavoidusingimplementationdefinedfeatures.

Deleted: unexpected

Comment [SGM18]: Huh?

Deleted: special

Page 50: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

44 ©ISO/IEC2017–Allrightsreserved

Thefollowingcodeshowsanexampleofrelianceuponimplementation-definedbehaviour:unsigned char x = 100; x += (x << 2) + 1; // x = 5x + 1

Sincethewidthofunsignedcharisimplementation-defined,thecomputationonxwillyielddifferentresultsforimplementationswithdifferentwidths.6.57.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.57.5.• Eliminatetotheextentpossibleanyrelianceonimplementation-definedbehaviourfromprogramsin

ordertoincreaseportability.Evenprogramsthatarespecificallyintendedforaparticularimplementationmayinthefuturebeportedtoanotherenvironmentorsectionsreusedforfutureimplementations.

6.58Deprecatedlanguagefeatures[MEM]

6.58.1ApplicabilitytolanguageCdeprecatedonefunction,thefunctiongets()andremoveditfromthestandardin2011.Chasdeprecatedseverallanguagefeaturesprimarilybytighteningtherequirementsforthefeature:

• Implicitintdeclarationsarenolongerallowed.• Functionscannotbeimplicitlydeclared.Theymustbedefinedbeforeuseorhaveaprototype.• Theuseofthefunctionungetc()atthebeginningofabinaryfileisdeprecated.• Areturnwithoutexpressionisnotpermittedinafunctionthatreturnsavalue(andviceversa).

6.58.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.58.5.• Althoughbackwardcompatibilityissometimesofferedasanoptionforcompilerssoonecanavoid

changestocodetobecompliantwithcurrentlanguagespecifications,updatingthelegacysoftwaretothecurrentstandardisabetteroption.

6.59Concurrency–Activation[CGA]

6.59.1Applicabilitytolanguage

TheCstandard,inclause7.26.5.1,requiresaconformingimplementationtosetspecificreturncodestoindicatewhetherornotathreadactivationsucceeded;thereforethevulnerabilitydoesnotapplytotheClanguage.

However,iftheprogramfailstocheckthereturncodeandfailstotakeappropriateactiontohandleafailedthreadcreation,thevulnerabilitydescribedinclause6.36applies.

Deleted: (NOTE)Thedeprecationofaliasedarrayparametershasbeenremoved,hencearrayparametersmaybealiased.

Deleted: (Deleted: theDeleted: )

Page 51: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 45

6.59.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.59.5.

6.60Concurrency–Directedtermination[CGT]

ThisvulnerabilitydoesnotapplytoCbecauseCdoesnotimplementamechanismtodirectlyterminateathread.Asimilareffectmaybeachievedbyaglobalflagrequestingthatathreadterminateitself,butthethreadisresponsibletoensurethatthatsuchterminationdoesn’toccuruntilallcriticalactivitiesarecompleted.

6.61Concurrentdataaccess[CGX]

6.61.1Applicabilitytolanguage

Asstatedinclause5.1.2.4oftheCstandard,aprogramthatcontainsadataraceexhibitsundefinedbehaviour.Inadditiontothreads,signalhandlersalsoposeariskofconcurrentdataaccess.Itistheresponsibilityoftheapplicationtouseatomicvariablesormutexestoensurethatonethreadorsignalhandlercannotmodifyanobjectwhileanotherthreadorsignalhandlerisattemptingtoaccessthesameobject.Forsignalhandling,“volatilesig_atomic_t”oratomicvariablescanbeusedtopreventthisvulnerability.

6.61.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.61.5.• Useatomicvariableswhereappropriatetoavoiddataraces.• Usemutexesappropriatelytoprotectaccessestonon-atomicsharedobjects.Wheremutexesareused,

theprogrammermustshowthattherearenopathsintheprogramwhereareleasecanbemissed,eitherbecauseofconditionalcodeorothermechanisms.

• UsemutexestomodelHoaremonitorsorsimilarhighlevelabstractionsofsynchronization.• Use“volatilesig_atomic_t”toprotectdatasharedwithsignalhandlersinasingle-threadedenvironment.

6.62Concurrency–Prematuretermination[CGS]

6.62.1Applicabilitytolanguage

ThisvulnerabilityappliestoCbecausethestandarddoesnotprovideamechanismtodeterminewhetherathreadhasterminated.

6.62.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.62.5.• Uselow-leveloperatingsystemprimitivesorotherAPIswhereavailabletocheckthatarequiredthreadis

stillactive.

Page 52: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

46 ©ISO/IEC2017–Allrightsreserved

6.63Lockprotocolerrors[CGM]

6.63.1Applicabilitytolanguage

ApplicationsinCmaycontainlockprotocolerrorssuchasamissingreleaseofamutex.SeeTR24772-1clause6.63fordescriptionsandmitigationsofprotocollockerrors.

6.63.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.63.5.• Beawareoftheoperationofeachsynchronizationmechanism,suchasthecaseswhereaccessesto

atomicvariablesmayoccurmorethanonceinastatement.

6.64UncontrolledFormatStrings[SHL]

6.64.1Applicabilitytolanguage

ThestandardClibrariesprovidealargefamilyofinputandoutputfunctionsthatuseacontrolstringtointerpretthedatareadorformattheoutput.ThesestringsincludeallthefeaturedescribedinTR24772-1clause6.64.1.

6.64.2Guidancetolanguageusers

• FollowtheguidelinesofTR24772-1clause6.64.5.

7.LanguagespecificvulnerabilitiesforC

[Intentionallyblank]

8.Implicationsforstandardization

Futurestandardizationeffortsshouldconsider:• Movinginthedirectionovertimetobeingamorestronglytypedlanguage.Muchoftheuseofweak

typingissimplyconveniencetothedeveloperinnothavingtofullyconsiderthetypesandusesofvariables.Strongertypingforcesgoodprogrammingdisciplineandclarityaboutvariableswhileatthesametimeremovingmanyunexpectedruntimeerrorsduetoimplicitconversions.ThisisnottosaythatCshouldbestrictlyastronglytypedlanguage–someadvantagesofCareduetotheflexibilitythatweakertypingprovides.Itissuggestedthatwhenenforcementofstrongtypingdoesnotdetractfrom

Formatted: Highlight

Comment [CP19]: Myviewisthatthisshouldbedeleted–ThisisWG14’sjob,notours

Page 53: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 47

thegoodflexibilitythatCoffers(forexample,addinganintegertoacharactertostepthroughasequenceofcharacters)andisonlyaconvenienceforprogrammers(forexample,addinganintegertoafloating-pointnumber),thenthestandardshouldspecifythestrongertypedsolution.

• AcommonwarninginAnnexIshouldbeaddedforfloating-pointexpressionsbeingusedinaBooleantestforequality.

• ModifyingordeprecatingmanyoftheCstandardlibraryfunctionsthatmakeassumptionsabouttheoccurrenceofastringterminationcharacter.

• Defineastringconstructthatdoesnotrelyonthenullterminationcharacter.• Defininganarraytypethatdoesautomaticboundschecking.• Deprecatinglesssafefunctionssuchasstrcpy()andstrcat()whereamoresecurealternativeisavailable.• Definingsaferandmoresecurereplacementfunctionssuchasmemncpy()andmemncmp()to

complementthememcpy()andmemcmp()functions(see6.11.6Implicationsforstandardization)• Defininganarraytypethatdoesautomaticboundschecking.• Definingfunctionsthatcontainanextraparameterinmemcpy()andmemmove()forthemaximum

numberofbytestocopy.Inthepast,somehavesuggestedthatthesizeofthedestinationbufferbeusedasanadditionalparameter.Somecriticsstatethatthissolutioniseasytocircumventbysimplyrepeatingtheparameterthatwasusedforthenumberofbytestocopyastheparameterforthesizeofthedestinationbuffer.Thisanalysisandcriticismiscorrect.Whatisneededisafailsafecheckastothemaximumnumberofbytestocopy.Thereareseveralreasonsforcreatingnewfunctionswithanadditionalparameter.Thiswouldmakeiteasierforstaticanalysistoeliminatethosecaseswherethememorycopycouldnotbeaproblem(suchaswhenthemaximumnumberofbytesisdemonstrablylessthanthecapacityofthereceivingbuffer).Manualanalysisormoreinvolvedstaticanalysiscouldthenbeusedfortheremainingsituationswherethesizeofthedestinationbuffermaynotbesufficientforthemaximumnumberofbytestocopy.Thisextraparametermayalsohelpindeterminingwhichcopiescouldtakeplaceamongobjectsthatoverlap.SuchcopyingisundefinedaccordingtotheCstandard.Itissuggestedthatsaferversionsoffunctionsthatincludearestrictionmax_nonthenumberofbytesntocopy(forexample,void*memncpy(void*restricts1,constvoid*restricts2,size_tn),constsize_tmax_n)beaddedtothestandardinadditiontoretainingthecurrentcorrespondingfunctions(forexample,memcpy(void*restricts1,constvoid*restricts2,size_tn))).Theadditionalparameterwouldbeconsistentwiththecopyingfunctionpairsthathavealreadybeencreatedsuchasstrcpy()/strncpy()andstrcat()/strncat().Thiswouldallowasaferversionofmemorycopyingfunctionsforthoseapplicationsthatwanttousethemintofacilitatebothsaferandmoresecurecodeandmoreefficientandaccuratestaticcodereviews7.

• Restrictionsonpointerarithmeticthatcouldeliminatecommonpitfalls.Pointerarithmeticiserror-proneandtheflexibilitythatitoffersisuseful,butsomeoftheflexibilityissimplyashortcutthatifrestrictedcouldlessenthechanceofapointerarithmeticbasederror.

• Definingastandardwayofdeclaringanattributetoindicatethatavariableisintentionallyunused.• AcommonwarninginAnnexIshouldbeaddedforvariableswiththesamenameinnestedscopes.• Creatingafewstandardizedprecedenceorders.Standardizingonafewprecedenceorderswillhelpto

eliminatetheconfusingintricaciesthatexistbetweenlanguages.Thiswouldnotaffectcurrentlanguages

7ThishasbeenaddressedbyWG14inanoptionallynormativeannexinthecurrentworkingpaper

Formatted: Highlight

Page 54: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

48 ©ISO/IEC2017–Allrightsreserved

asalteringprecedenceordersinexistinglanguagesistooonerous.However,thiswouldsetabasisforthefutureasnewlanguagesarecreatedandadopted.Statingthatalanguageuses“ISOprecedenceorderA”wouldbeusefulratherthanhavingtospellouttheentireprecedenceorderthatdiffersinaconceptuallyminorwayfromsomeotherlanguages,butinamajorwaywhenprogrammersattempttoswitchbetweenlanguages.

• Deprecatingthegotostatement.Theuseofthegotoconstructisoftenspotlightedastheantithesisofgoodstructuredprogramming.ThoughitsdeprecationwillnotinstantlymakeallCcodestructured,deprecatingthegotoandleavinginplacetherestrictedgotovariations(forexample,breakandcontinue)andpossiblyaddingotherrestrictedgoto’scouldassistinencouragingsaferandmoresecureCprogrammingingeneral.

• Defininga“fallthru”constructthatwillexplicitlybindmultipleswitchcasestogetherandeliminatetheneedforthebreakstatement.Thedefaultwouldbeforacasetobreakinsteadoffallingthroughtothenextcase.Grantedthisisamajorshiftinconcept,butifitcouldbeaccomplished,lessunintentionalerrorswouldoccur.

• DefininganidentifiertypeforloopcontrolthatcannotbemodifiedbyanythingotherthantheloopcontrolconstructwouldbearelativelyminoradditiontoCthatcouldmakeCcodesaferandencouragebetterstructuredprogramming.

• DefiningastandardizedinterfacepackageforinterfacingCwithmanyofthetopprogramminglanguagesandareciprocalpackageshouldbedevelopedoftheothertoplanguagestointerfacewithC.

• Joiningwithotherlanguagesindevelopingastandardizedsetofmechanismsfordetectingandtreatingerrorconditionssothatalllanguagestotheextentpossiblecouldusethem.Notethatthisdoesnotmeanthatalllanguagesshouldusethesamemechanismsasthereshouldbeavariety(labelparameters,auxiliarystatusvariables),buteachofthemechanismsshouldbestandardized.

• Sincefaulthandlingandexitingofaprogramiscommontoalllanguages,itissuggestedthatcommonterminologysuchasthemeaningoffailsafe,failhard,failsoft,andsoonalongwithacoreAPIsetsuchasexit,abort,andsoonbestandardizedandcoordinatedwithotherlanguages.

• Deprecatingunions.Theprimaryreasonfortheuseofunionstosavememoryhasbeendiminishedconsiderablyasmemoryhasbecomecheaperandmoreavailable.Unionsarenotstaticallytypesafeandarehistoricallyknowntobeacommonsourceoferrors,leadingtomanyCprogrammingguidelinesspecificallyprohibitingtheuseofunions.

• Creatingarecognizablenamingstandardforroutinessuchthatoneversionofalibrarydoesparametercheckingtotheextentpossibleandanotherversiondoesnoparameterchecking.Thefirstversionwouldbeconsideredsaferandmoresecureandthesecondcouldbeusedincertainsituationswhereperformanceiscriticalandthecheckingisassumedtobedoneinthecallingroutine.Anamingstandardcouldbemadesuchthatthelibrarythatdoesparametercheckingcouldbenamedasusual,say“library_xyz”andanequivalentversionthatdoesnotdocheckingcouldhavea“_p”appended,suchas“library_xyz_p”.Withoutanamingstandardsuchasthis,aconsiderablenumberofwastedcycleswillbeconducteddoingadoublecheckofparametersorevenworse,nocheckingwillbedoneinboththecallingandreceivingroutinesaseachisassumingtheotherisdoingthechecking.

• CreatinganAnnexthatlistsdeprecatedfeatures.

Page 55: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

©ISO/IEC2017–Allrightsreserved 49

Bibliography

[1] ISO/IECDirectives,Part2,RulesforthestructureanddraftingofInternationalStandards,2004

[2] ISO/IECTR10000-1,Informationtechnology—FrameworkandtaxonomyofInternationalStandardized

Profiles—Part1:Generalprinciplesanddocumentationframework

[3] ISO10241(allparts),Internationalterminologystandards

[4] ISO/IEC9899:2011,Informationtechnology—Programminglanguages—C

[5] ISO/IEC9899:2011/Cor.1:2012,TechnicalCorrigendum1

[6] ISO/IEC/IEEE60559:2011,Informationtechnology–MicroprocessorSystems–Floating-Pointarithmetic

[7] R.Seacord,TheCERTCSecureCodingStandard.Boston,MA:Addison-Westley,2008.

[8] MotorIndustrySoftwareReliabilityAssociation.GuidelinesfortheUseoftheCLanguageinVehicleBasedSoftware,2012(thirdedition)16F

.

[9] ISO/IECTR24731–1,Informationtechnology—Programminglanguages,theirenvironmentsandsystem

softwareinterfaces—ExtensionstotheClibrary—Part1:Bounds-checkinginterfaces

[10] L.Hatton,SaferC:developingsoftwareforhigh-integrityandsafety-criticalsystems.McGraw-Hill1995

[11] SoftwareConsiderationsinAirborneSystemsandEquipmentCertification.IssuedintheUSAbytheRequirementsandTechnicalConceptsforAviation(documentRTCASC167/DO-178B)andinEuropebytheEuropeanOrganizationforCivilAviationElectronics(EUROCAEdocumentED-12B).December1992.

[12] IEC61508:Parts1-7,Functionalsafety:safety-relatedsystems.1998.(Part3isconcernedwithsoftware).

[13] ISO/IEC15408:1999Informationtechnology.Securitytechniques.EvaluationcriteriaforITsecurity.

[14] Hogaboom,Richard,AGenericAPIBitManipulationinC,EmbeddedSystemsProgramming,Vol12,No7,July1999http://www.embedded.com/1999/9907/9907feat2.htm

[15] Seacord,R.SecureCodinginCandC++.Boston,MA:Addison-Wesley,2005.Seehttp://www.cert.org/books/secure-codingfornewsanderrata.

[16] TheCommonWeaknessEnumeration(CWE)Initiative,MITRECorporation,(http://cwe.mitre.org/)

[17] ISO/IECTS17961,Informationtechnology–Programminglanguages,theirenvironmentsandsystem

softwareinterfaces–Csecurecodingrules

[18] Kernighan,Ritchie,TheCProgrammingLanguage(1stEdition),PrenticeHall1978

Deleted:

Deleted: Formatted: Indent: Left: 0 cm, First line: 0 cm

Deleted: Deleted: 5

Page 56: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

WG23/N0740

50 ©ISO/IEC2017–Allrightsreserved

Index

CGM–LockprotocolErrors,45CGS–Concurrency–Prematuretermination,44LanguageVulnerabilities

Concurrency–Prematuretermination[CGS],44LockprotocolErrors[CGM],45

Uncontrolledformatstring[SHL],45rsize_t,13SHL–Uncontrolledformatstring,45size_t,13

Page 57: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

Page 4: [1] Deleted Clive Pygott 12/22/17 3:22:00 PM

Note:Abit-fieldandanadjacentnon-bit-fieldmemberareinseparatememorylocations.Thesameappliestotwobit-fields,ifoneisdeclaredinsideanestedstructuredeclarationandtheotherisnot,orifthetwoareseparatedbyazero-lengthbit-fielddeclaration,oriftheyareseparatedbyanon-bit-fieldmemberdeclaration.Itisnotsafetoconcurrentlyupdatetwobit-fieldsinthesamestructureifallmembersdeclaredbetweenthemarealsobit-fields,nomatterwhatthesizesofthoseinterveningbit-fieldshappentobe.Forexampleastructuredeclaredas struct { char a; int b:5, c:11, :0, d:8; struct { int ee:8; } e; } containsfourseparatememorylocations:Themembera,andbit-fieldsdande.eeareseparatememorylocations,andcanbemodifiedconcurrentlywithoutinterferingwitheachother.Thebit-fieldsbandctogetherconstitutethefourthmemorylocation.Thebit-fieldsbandccan’tbeconcurrentlymodified,butbanda,canbeconcurrentlymodified[CP1]

Page 7: [2] Deleted Clive Pygott 12/22/17 3:33:00 PM

Everyguidanceprovidedinthissection,andinthecorrespondingPartsection,issupportedmaterialinClause6ofthisdocument,aswellasotherimportantrecommendations.

Page 7: [3] Deleted Clive Pygott 11/21/17 5:00:00 PM

Example:s=(structfoo*)malloc(sizeof(structfoo));usestheCtypesystemtoenforcethatthepointertotheallocatedspacewillbeofatypethatisappropriateforthesize.Becausemallocreturnsavoid *,withoutthecast,"s"couldbeofanyrandompointertype,withthecast,thatmistakewillbecaught

Page 9: [4] Deleted Clive Pygott 12/22/17 3:37:00 PM

Theintegerconversionrankisusedintheusualarithmeticconversionstodeterminewhatconversionsneedtotakeplacetosupportanoperationonmixedintegertypes.

Otherconversionrulesexistforotherdatatype-conversions.Soeventhoughtherearerulesinplaceandtherulesareratherstraightforward,thevarietyandcomplexityoftherulescancauseunexpectedresultsandpotentialvulnerabilities.Forexample,thoughthereisaprescribedorderinwhich

Page 58: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

conversionswilltakeplace,determininghowtheconversionswillaffectthefinalresultcanbedifficultasinthefollowingexample: long foo (short a, int b, int c, long d, long e, long f) { return (((b + f) * d – a + e) / c); } Theimplicitconversionsperformedinthereturnstatementcanbenontrivialtodiscern,butcangreatlyimpactwhetheranyoftheintermediatevaluesoverflowduringthecomputation.

Page 10: [5] Deleted Clive Pygott 11/21/17 5:03:00 PM

Beawarethatimplicitcastsmaymaketheresultingtypeofanexpressionfloating-point[CP2]. Donotconvertafloating-pointnumbertoanintegerunlesstheconversionisaspecified

algorithmicrequirementorisrequiredforahardwareinterface[CP3].

Page 18: [6] Deleted Clive Pygott 11/22/17 5:46:00 PM

Inparticular,makecastsexplicitinthereturnvalueofmallocExample:s = (struct foo*)malloc(sizeof(struct foo)); ThisusestheCtypesystemtoenforcethatthepointertotheallocatedspacewillbeofatypethatisappropriateforthesize.Becausemallocreturnsavoid *,withoutthecast,scouldbeofanyrandompointertype;withthecast,thatmistakewillbecaught

Page 20: [7] Deleted Clive Pygott 12/23/17 4:04:00 PM

dynamic

Page 22: [8] Deleted Clive Pygott 12/18/17 2:42:00 PM

Cisoftenusedforbitmanipulation.PartofthisisduetothecapabilitiesinCtomaskbitsandshiftthem.AnotherpartisduetotherelativeclosenessChastoassemblyinstructions.Manipulatingbitsonasignedvaluecaninadvertentlychangethesignbitresultinginanumberpotentiallygoingfromapositivevaluetoanegativevalue.

Page 23: [9] Deleted Clive Pygott 12/18/17 2:47:00 PM

Keepinmindthatcodewillbereusedandcombinedinwaysthattheoriginaldevelopersneverimagined.

MakenamesdistinguishablewithinthefirstfewcharactersduetoscopinginC.Thiswillalsoassistinavertingproblemswithcompilersresolvingtoashorternamethanwasintended.

Page 25: [10] Deleted Clive Pygott 12/19/17 9:58:00 AM

Page 59: Information Technology — Programming languages — …...multiples of a byte address 3.1.3 argument expression in the comma-separated list bounded by the parentheses in a function

Ensurethatadefinitionofanentitydoesnotoccurinascopewhereadifferententitywiththesamenameisaccessibleandhasatypethatpermitsittooccurinatleastonecontextwherethefirstentitycanoccur.

Ensurethatallidentifiersdifferwithinthenumberofcharactersconsideredtobesignificantbytheimplementationsthatarelikelytobeused,anddocumentallassumptions.

Page 27: [11] Deleted Clive Pygott 12/19/17 10:22:00 AM

Cprovidessignificantoffreedominconstructingstatements.Thisfreedom,ifmisused,canresultinunexpectedresultsandpotentialvulnerabilities.TheflexibilityofCcanobscuretheintentofaprogrammer.

Page 32: [12] Deleted Clive Pygott 12/20/17 10:22:00 AM

Encouragetheuseofasingleexitpointfromafunction.