1. 首页
  2. 课程学习
  3. C++/C
  4. C Traps and Pitfalls

C Traps and Pitfalls

上传者: 2019-09-26 13:00:18上传 PDF文件 5.35MB 热度 19次
C Traps and Pitfalls C陷阱与缺陷To Barbarawho for too longhas had to endurea house full of draftsPREFACETools that are comfortable after experience are often more difficult tolearn at first than those that feel right immediately. Student pilots startout overcontrolling turning first flights into roller-coaster rides, untilthey learn how light a touch flying really requires. Training wheels on abicycle make it easier for a novice to ride but get in the way after thatSo it is also with programming languages. Every programminglanguage has aspects that are most likely to cause trouble for people notyet thoroughly familiar with them. These aspects vary from onelanguage to another but are surprisingly constant from one programmerto another. Thus the idea of collecting themMy first effort to collect such problems was in 1977, when i gave atalk called PL/I Traps and Pitfalls at the ShARE (IBM mainframe usersgroup)meeting in Washington DC. That was shortly after I moved fromColumbia University, where people used PL/I heavily, to aT&T BellLaboratories, where people use C heavily. The decade that followed gaveme ample experience in how C programmers (including me)can getthemselves into trouble if theyre not certain of what theyre doingI started collecting C problems in 1985 and published the collection asan internal paper at the end of that year. The response astonished memore than 2,000 people requested copies of the paper from the Bell labslibrary. That convinced me to expand the paper into this bookWhat this book isC Traps and Pitfalls aims to encourage defensive programming by showinghow other people, even experienced professionals, have gotten them-selves into trouble. These mistakes are generally easy to avoid once seenand understood, so the emphasis is on specific examples rather than generalitiesThis book belongs on your shelf if you are using c at all seriouslyV1 C TRAPS AND PITFALLSPREFACEeven if you are an expert: many of the professional C programmers whosaw early drafts said things like that bug bit me just last week! If youare teaching a course that uses C, it belongs at the top of your supple-mentary reading listWhat this book is notThis book is not a criticism of C. programmers can get themselves intotrouble in any language i have tried here to distill a decade of c experi-ence into a compact form in the hope that you, the reader, will be able toavoid some of the stupid mistakes i've made and seen others makeThis book is not a cookbook. Errors cannot be avoided by recipe. Ifthey could, we could eliminate automobile accidents by plastering thecountryside with Drive Carefully signs! People learn most effectivelythrough experience their own or someone elses. Merely understanding how a particular kind of mistake is possible is a big step on the wayto avoiding it in the futureThis book is not intended to teach you how to program in C(see Kernighan and Ritchie: The C Prrogramming language, second editionPrentice-Hall 1988), nor is it a reference manual(see Harbison and SteeleC: A Reference Manual, second edition, Prentice-Hall 1987). It does notmention algorithms or data structures(see Van Wyk: Data Structures and CPrograms, Addison-Wesley 1988), and only briefly discusses portability(see Horton How to Write Portable programs in C, Prentice-Hall 1989)andoperating system interfaces(see Kernighan and Pike: The UNIX Program-ming Environment, Prentice-Hall 1984). The problems mentioned are realalthough often shortened (for a collection of composed C problems seeFeuer: The C Puzzle Book, Prentice-Hall 1982). It is neither a dictionarynor an encyclopedia i have kept it short to encourage you to read it allYour name in lightsI'm sure Ive missed some pitfalls. If you find one I've missed, pleasecontact me via Addison-Wesley. I may well include your discovery, withan acknowledgment, in a future editionA word about ANSI CAs I write this, the anSi C standard is not yet final. It is technicallyincorrect to refer to ANSi C until the ansi committee finishes itswork. In practice, though, the aNSI standard is far enough along thatnothing I say about anSi C is likely to change. C compilers are alreadyavailable that implement many of the significant improvements contemplated by the aNSi committeePREFACEC TRAPS AND PITFALLSDon't worry if your C implementation does not support the ANSIfunction syntax mentioned here: is it easy enough to understand the partsof the examples where it matters, and you can fall into the trapsdescribed there regardless of what version of c you useAcknowledgmentsa collection like this could not possibly have been made in isolationPeople who have pointed out particular pitfalls include Steve Bellovin(S6.3, p.82), Mark Brader (s1.1, p.6), Luca Cardelli(54.4, p. 62), LarryCipriani (52.3, p 21), Guy Harris and Steve Johnson($2.2, p. 20), Phil Karn(S2.2, p.17), Dave Kristol($7.,p 90), George W. Leach(s1. 1, p7), DougMcllroy( 52.3, p 21), Barbara Moo($7. 2, p. 88), Rob Pike(s1.1, p.6),JimReeds($3.6, P. 36), Dennis Ritchie($2. 2, p 19), Janet Sirkis(55.2, p70),Richard Stevens($2.5, P 24), Bjarne Stroustrup(52.3, p. 20), Ephraim Vish-niac (S1.4, p9),and one contributor who wishes to remain anonymous(S2.3, P. 22). For brevity, I've mentioned only the first person to reportany particular problem to me. Of course, I doubt any of the people Ivementioned actually invented the programming errors they pointed out tome,and if they did i doubt theyd admit it! I know I've made many ofthem myself too some several timesUseful editorial suggestions came from Steve Bellovin, Jim Coplien,Marc Donner, Jon Forrest, Brian Kernighan, Doug McIlroy, Barbara Moo,Rob Murray, Bob Richton, Dennis Ritchie, Jonathan Shapiro, and severalanonymous reviewers. Lee McMahon and Ed Sitar pointed out whatwould otherwise have been embarrassing typographical errors in earlydrafts of the manuscript. Dave Prosser clarified many fine points ofANSI C for me. Brian Kernighan supplied invaluable typesetting toolsand assistanceIt has been a delight to work with the people at Addison-Wesley,including Jim DeWolf, Mary Dyer, Lorraine Ferrier, Catherine Harutunian, Marshall Henrichs, Debbie Lafferty, Keith Wollman, and helenWythe. I'm sure they've gained from the aid of others whom I haventmeti am particularly grateful to the enlightened managers at at&T bellLaboratories who made it possible for me to write this book at all, includ-ing Steve Chappell, Bob Factor, Wayne Hunt, Rob Murray, Will Smith,Dan Stanzione and Eric SumnerThe title of this book was suggested by Robert Sheckley's sciencefiction anthology The People Trap and Other Pitfalls, Snares, Devices, andDelusions(as well as two Sniggles and a Contrivance), published by DellBooks in 1968CONTENTS0 Introduction……....1...11 Lexical pitfalls51.1is not =1.2 and i are not & or i i71. 3 Greedy lexical analysis71. 4 Integer constants1.5 Strings and characters……102 Syntactic pitfalls…………132. 1 Understanding function declarations132.2 Operators dont always have the precedence you want..172.3 Watch those semicolons!202.4 The switch statement2225 Calling functions…………2426 The dangling else problem…….243 Semantic pitfalls..3. 1 Pointers and arrays3.2 Pointers are not arrays323. 3 Array declarations as parameters333.4 Eschew synecdoche343.5 Null pointers are not null strings353.6 Counting and asymmetric b363.7 Order of evaluation463. 8 The&&,H, and I operators3.9 Integer overflow...493.10 Returning a value from main……,…,…………50X C TRAPS AND PITFALLSCoNTENTS4 Linkage........1534. 1 What is a linker?534.2 Declarations vs definitions544.3 Name conflicts and the static modifier....,564.4 Arguments, Parameters, and return values574.5 Checking external types634.6 Header files5 Library functions .5. I getchar returns an integer....705.2 Updating a sequential file…705.3 Buffered output and memory allocation725.4 Using errno for error detection735.5 The signal function746 The preprocessor776.1 Spaces matter in macro definitions6.2 Macros are not functions6.3 Macros are not statements6.4 Macros are not type definitions837 Portability pitfalls….…●。曲品自自山备卓·●·●导●●·命●中···垂命非是非8571 Coping with change…857.2 What's in a name?7.3 How big is an integer?887.4 Are characters signed or unsigned?97.5 Shift operators7.6 Memory location zero917. How does division truncate?7. 8 How big is a random number?937.9 Case conversion937.10 Free first, then reallocate?7.11 An example of portability problems968 Advice and answers.8.1 Advice1028.2 Answers105
用户评论