Table Of Contenti
INTRODUCTION
C
Richard Heathfield
Lawrence Kirby
et al.
A Division of Macmillan USA
201 West 103rd Street
Indianapolis, Indiana 46290
C
ii
UNLEASHED
C Unleashed EXECUTIVEEDITOR
RosemarieGraham
Copyright# 2000bySamsPublishing
FontSILSophialPA93usedinChapter25iscopyrightedbytheSummerInstitute ACQUISITIONSEDITOR
ofLinguistics,7500W.CampWisdomRoad,DallasTX75236,usedwith CarolAckerman
permission.
DEVELOPMENTEDITOR
Allrightsreserved.Nopartofthisbookshallbereproduced,storedinaretrieval GusA.Miklos
system,ortransmittedbyanymeans,electronic,mechanical,photocopying,
recording,orotherwise,withoutwrittenpermissionfromthepublisher.Nopatent MANAGINGEDITOR
liabilityisassumedwithrespecttotheuseoftheinformationcontainedherein. MattPurcell
Althougheveryprecautionhasbeentakeninthepreparationofthisbook,the
publisherandauthorsassumenoresponsibilityforerrorsoromissions.Neitheris SENIOREDITOR
anyliabilityassumedfordamagesresultingfromtheuseoftheinformation KarenA.Walsh
containedherein.
COPYEDITOR
InternationalStandardBookNumber:0-672-31896-2 KimCofer
LibraryofCongressCatalogCardNumber:99-068209
INDEXER
PrintedintheUnitedStatesofAmerica DianeBrenner
FirstPrinting:July2000
PROOFREADERS
02 01 00 4 3 2 1 JuliCook
CandiceHightower
Trademarks
MattWynalda
Alltermsmentionedinthisbookthatareknowntobetrademarksorservice
TECHNICALEDITORS
markshavebeenappropriatelycapitalized.SamsPublishingcannotattesttothe
SteveKrattiger
accuracyofthisinformation.Useofaterminthisbookshouldnotberegardedas
PeterSeebach
affectingthevalidityofanytrademarkorservicemark.
VinayPai
ThispublicationwasproducedusingtheAdvent3B2PublishingSystem.
SOFTWAREDEVELOPMENT
Warning and Disclaimer
SPECIALIST
Everyefforthasbeenmadetomakethisbookascompleteandasaccurateas WilliamC.ElandJr.
possible,butnowarrantyorfitnessisimplied.Theinformationprovidedisonan
INTERIORDESIGN
‘‘asis’’basis.Theauthorsandthepublishershallhaveneitherliabilityor
GaryAdair
responsibilitytoanypersonorentitywithrespecttoanylossordamagesarising
fromtheinformationcontainedinthisbookorfromtheuseoftheCDor COVERDESIGN
programsaccompanyingit.
ArenHowell
COPYWRITER
EricBorgert
3B2DESIGN
MichelleMitchell
DanielaRaderstorf
3B2LAYOUTTECHNICIANS
SusanGeiselman
BradLenser
iii
INTRODUCTION
Contents at a Glance
PART I The C Language Revisited 1
1 C ProgrammerUnleashed! 3
2 Holy Wars:ProgrammingStandards—Causes andCures 21
3 Optimization 75
4 Dealing withDates 113
5 Playing withBitsandBytes 131
6 OfflineData StorageandRetrieval 161
7 When ThingsGoWrong:Code-Mending 203
8 Managing Memory 259
9 Simulations andControllers 299
10 Recursion 315
PART II Data Organization 341
11 SimpleAbstract DataStructures 343
12 Binary SearchTrees 455
13 Rapid SortingTechniques 507
14 Tries 571
15 Sparse Matrix 591
16 WorkingwithGraphs 641
PART III Advanced Topics 709
17 Matrix Arithmetic 711
18 DigitalSignalProcessing 759
19 Expression ParsingandEvaluation 839
20 MakingSoftwareTools 911
21 Genetic Algorithms 977
22 Cross-Platform Development:CommunicationsProgramming 1001
23 WritingCommonGateway Interface(CGI)Applicationsin C 1053
24 Arbitrary PrecisionArithmetic 1087
C
iv
UNLEASHED
25 NaturalLanguageProcessing 1139
26 Encryption 1171
27 EmbeddedSystems 1209
28 ParallelProcessing 1225
29 Lookingto theFuture:C99 1243
PART IV Part IV Appendixes 1259
A GNU GeneralPublicLicense 1261
B SelectedBibliography 1269
Index 1273
v
CONTENTS
Contents
PART I The C Language Revisited 1
1 C Programmer Unleashed! 3
WhoShouldRead ThisBook? ...................................... 5
WhatKnowledge IsAssumed? ...................................... 6
Howto GettheMost fromThisBook................................ 8
WhyAnother BookAbout C?....................................... 9
WhyANSI C?.................................................... 10
WhatPlatformsDoes ThisBookCover?............................. 11
About theSource Codein ThisBook ............................... 11
Code Quality ..................................................... 12
HowThisBook IsOrganized....................................... 12
CopyrightIssues .................................................. 14
On theCD........................................................ 15
The CProgrammingCommunity ................................... 15
Summary......................................................... 19
2 Holy Wars: Programming Standards—Causes and Cures 21
Bracing Styles .................................................... 23
1TBS ......................................................... 23
Allman........................................................ 23
Whitesmith.................................................... 24
GNU.......................................................... 24
Use ofWhitespace ................................................ 26
Indentation .................................................... 26
TabsandMainframeCompilers.................................. 27
WhitespaceAround Tokens ..................................... 27
CosmeticCode Fixes........................................... 28
Structured Programming ........................................... 29
goto.......................................................... 29
break......................................................... 30
continue...................................................... 30
while(1)...................................................... 31
return........................................................ 32
Initialization ...................................................... 35
MultipleDefinitionsonOne Line................................ 35
Initializationat Definition....................................... 36
C
vi
UNLEASHED
StaticsandGlobals.................................................38
ProblemswithRe-use...........................................39
IdentifierNames...................................................40
Length.........................................................40
Intelligibility ...................................................41
ReservedNames................................................42
Prefixes:the‘‘TransylvanianHeresy’’.............................44
NamingVariables...............................................45
NamingConstants ..............................................46
NamingTypes..................................................46
NamingMacros ................................................47
NamingFunctions ..............................................47
WritingUseful Comments..........................................48
CommentLayoutStyles.........................................49
WhenNotto Comment..........................................51
CommentWhattheCode Does ..................................51
CommentComplexCode........................................52
CommentClosingBraces........................................52
Don’t‘‘CommentOut’’ Code....................................53
CommonErrorsandMisunderstandings..............................53
Thevoidmain Heresy...........................................54
NumberofArguments for main() ...............................56
IntegerMathVersusFloatingPointMath..........................57
SignalHandling ................................................58
PassingbyValue ...............................................58
ProblemswithUnions...........................................61
Thesizeof Operator............................................62
Thereturn Keyword ...........................................63
UnderstandingDeclarations, Definitions,andPrototypes...............63
Declarations....................................................63
Definitions.....................................................63
Prototypes......................................................64
TheImportanceofPortability.......................................64
OnesandTwosComplement.....................................65
DefiningUndefinedBehavior....................................65
SizesofIntegerTypes...........................................69
StructurePadding...............................................70
Macros ...........................................................71
CVersusC++.....................................................72
Summary .........................................................73
vii
CONTENTS
3 Optimization 75
The AppealofOptimizationandSomeAncient History............... 76
TimeWell Spent............................................... 76
CIs AlreadyaVeryFastLanguage.............................. 77
The ImportanceofMeasurements................................ 78
ThinkingAbout Performance....................................... 78
ASense ofPerspective ......................................... 78
O-Notation .................................................... 81
Profiling.......................................................... 85
FlatProfiling................................................... 86
Graphing Profilers.............................................. 87
Other ProfilingMethods ........................................ 89
AlgorithmicStrategiesforOptimization ............................. 90
RealityCheck.................................................. 91
ImplementationStrategiesforOptimization,orMicro-Optimizations. 91
SomeAdditionalOptimizationStrategies........................ 103
Cooperative andParallelOptimizations............................. 104
SomeNewMeasurements...................................... 105
Client/Server andParallelism................................... 105
ImplicitParallelism............................................ 107
User InterfaceConsiderationsfor
Time-ConsumingAlgorithms................................ 108
WhenNot toOptimize............................................ 110
Premature OptimizationIs theRootofAllEvil .................. 110
It isEasier toMakeaCorrect ProgramFastThan aFast
ProgramCorrect............................................ 110
Don’tOptimizeAway Portability ............................... 111
LettheCompilerDo It ........................................ 111
Summary........................................................ 112
4 Dealing with Dates 113
Date andTime Functions ......................................... 114
BasicDate andTimeFunctions................................. 114
Breaking DatesandTimesinto UsefulQuantities................. 116
SimpleTime StringFormatting................................. 117
ComplexTime Formatting ..................................... 118
Reading andManipulatingDates andTimes ..................... 121
MeasuringExecution Time..................................... 123
The MillenniumBug:Date-RelatedProblems....................... 124
Useful BitsandPieces............................................ 126
Leap Years ................................................... 126
ISO 8601:DateFormatsandWeekNumbers .................... 127
Summary........................................................ 129
C
viii
UNLEASHED
5 Playing with Bits and Bytes 131
RepresentationofValuesin C......................................132
TheRepresentation ofIntegerValues...............................133
UsingUnsignedTypeforBitManipulation..........................135
BitShifting ......................................................136
OtherBitOperators...............................................137
BitArrays (BitMaps).............................................140
BitCounting .....................................................144
BitMirroring.....................................................148
Bit-Fields........................................................151
Lookingat Portability.............................................153
Summary ........................................................159
6 Offline Data Storage and Retrieval 161
GoalsandApplications............................................162
TextandBinaryFormats .......................................163
StructuralIssues...............................................164
FormatDesignIssues ..........................................165
BasicTechniques.................................................166
TextFiles.....................................................166
BinaryFiles...................................................176
GenericFormats..................................................187
Whitespace-orTab-Delimited Files..............................187
Comma-SeparatedValues(CSV) ................................191
.iniFiles.....................................................194
AdvancedTechniques.............................................196
UpdatingRecords..............................................197
Indexing......................................................198
RelatedTopics....................................................200
Summary ........................................................202
7 When Things Go Wrong: Code-Mending 203
DealingwithDiagnostics..........................................204
UseWarningsWisely ..........................................205
Top-downApproach ...........................................210
LintIsYourFriend ............................................210
DebuggingCommon Errors........................................212
Off-by-One Errors .............................................217
FencepostErrors...............................................217
InfiniteLoops.................................................218
AssignmentInsteadofComparison..............................219
BufferOverflow...............................................220
ArrayBounds Violation ........................................222
ix
CONTENTS
MissingArguments............................................ 223
Pointers ...................................................... 224
DebuggingSoftware.............................................. 229
CommercialDebuggers........................................ 229
TraceMacros................................................. 230
Planto SucceedbyExpectingto Fail............................... 241
Debug-onlyCode ............................................. 242
UsingAssertion Statements .................................... 243
Compile-timeAssertions....................................... 246
The DebuggingProcess........................................... 247
KnowingWhatIs MeanttoHappen............................. 247
WatchingItHappen ........................................... 247
IdentifyingWhereIt Breaks.................................... 248
TypesofBugs ................................................ 249
BohrBugs.................................................... 250
Heisenbugs................................................... 251
Mandelbugs................................................... 253
Schroedinbugs ................................................ 253
A Programmer’s Nightmare ....................................... 255
Summary........................................................ 257
8 Managing Memory 259
WhatIs MemoryManagement?.................................... 260
CommonMemoryUsageErrors................................... 260
UsingMemoryYouDidn’tAllocate............................. 261
gets() FunctionConsideredHarmful........................... 263
FailingtoStore theAddress.................................... 263
NotChecking ReturnValues ................................... 265
NotUsing aSparePointerfor realloc.......................... 265
UsingMemoryYouNoLonger Own............................ 267
RelyingontheOS toReclaimMemory ......................... 268
WhenaMemoryAllocation FunctionFails......................... 269
Break DowntheMemoryRequirement.......................... 270
Use LessMemory............................................. 270
Use aFixed LengthBuffer..................................... 272
Allocate anEmergencyReserve ................................ 273
UsingDisk Space............................................. 273
Whatto Dowhen calloc Succeeds................................ 274
Stayingin Control................................................ 275
MemoryTrackingHeaderFile.................................. 277
ImplementingtheMemoryTrackingLibrary..................... 282
Redesigning realloc.......................................... 285
Unredesigning realloc........................................ 286