Home > Store

C Traps and Pitfalls

Register your product to gain access to bonus material or receive a coupon.

C Traps and Pitfalls

Book

  • Sorry, this book is no longer in print.
Not for Sale

Description

  • Copyright 1989
  • Dimensions: 6" x 9-1/4"
  • Pages: 160
  • Edition: 1st
  • Book
  • ISBN-10: 0-201-17928-8
  • ISBN-13: 978-0-201-17928-6

Even C experts come across problems that require days ofdebugging to fix. This book helps to prevent such problems byshowing how C programmers get themselves into trouble. Each ofthe book's many examples has trapped a professional programmer.

In addition to its examples, C Traps and Pitfalls offers adviceon:

  • avoiding off-by-one errors
  • understanding and constructing function declarations
  • understanding the subtle relationship between pointers andarrays

Distilled from the author's experience over a decade ofprogramming in C, this book is an ideal resource for anyone,novice or expert, who has ever written a C program.



0201179288B04062001

Sample Content

Table of Contents



Introduction.


1. Lexical Pitfalls.

= is not ==

& and | are not && or ||

Greedy lexical analysis.

Integer constants.

Strings and characters.



2. Syntactic pitfalls.

Understanding function declarations.

Operators don't always have the precedence you want.

Watch those semicolons!

The switch statement.

Calling functions.

The dangling else problem.



3. Semantic pitfalls.

Pointers and arrays.

Pointers are not arrays.

Array declarations as parameters.

Eschew synecdoche.

Null pointers are not null strings.

Counting and asymmetric bounds.

Order of evaluation.

The &&, ||, and ! operators.

Integer overflow.

Returning a value from main.



4. Linkage.

What is a linker?

Declarations vs. definitions.

Name conflicts and the static modifier.

Arguments, parameters, and return values.

Checking external types.

Header files.



5. Library functions.

Getchar returns an integer.

Updating a sequential file.

Buffered output and memory allocation.

Using errno for error detection.

The signal function.



6. The preprocessor.

Spaces matter in macro definitions.

Macros are not functions.

Macros are not statements.

Macros are not type definitions.



7. Portability pitfalls.

Coping with change.

What's in a name?

How big is an integer?

Are characters signed or unsigned?

Shift operators.

Memory location zero.

How does division truncate?

How big is a random number?

Case conversion.

Free first, then reallocate?

An example of portability problems.



8. Advice and answers.

Advice.

Answers.



Appendix: printf, varargs, and stdarg.

The printf family.

Simple format types.

Modifiers.

Flags.

Variable field width and precision.

Neologisms.

Anachronisms.

Variable argument lists with varargs.h.

Implementing varargs.h.

stdarg.h: the ANSI varargs.h. 0201179288T04062001

Preface

Tools that are comfortable after experience are often more difficult to learn at first than those that feel right immediately. Student pilots start out overcontrolling, turning first flights into roller-coaster rides, until they learn how light a touch flying really requires. Training wheels on a bicycle make it easier for a novice to ride, but get in the way after that.

So it is also with programming languages. Every programming language has aspects that are most likely to cause trouble for people not yet thoroughly familiar with them. These aspects vary from one language to another, but are surprisingly constant from one programmer to another. Thus the idea of collecting them.

My first effort to collect such problems was in 1977, when I gave a talk called PL/I Traps and Pitfalls at the SHARE (IBM mainframe users' group) meeting in Washington, DC. That was shortly after I moved from Columbia University, where people used PL/I heavily, to AT&T Bell Laboratories, where people use C heavily. The decade that followed gave me ample experience in how C programmers (including me) can get themselves into trouble if they're not certain of what they're doing.

I started collecting C problems in 1985 and published the collection as an internal paper at the end of that year. The response astonished me: more than 2,000 people requested copies of the paper from the Bell Labs library. That convinced me to expand the paper into this book.

What This Book Is

C Traps And Pitfalls aims to encourage defensive programming by showing how other people, even experienced professionals, have gotten themselves into trouble. These mistakes are generally easy to avoid once seen and understood, so the emphasis is on specific examples rather than generalities.

This book belongs on your shelf if you are using C at all seriously, even if you are an expert: many of the professional C programmers who saw early drafts said things like "that bug bit me just last week!" If you are teaching a course that uses C, it belongs at the top of your supplementary reading list. What This Book Is Not

This book is not a criticism of C. Programmers can get themselves into trouble in any language. I have tried here to distill a decade of C experience into a compact form in the hope that you, the reader, will be able to avoid some of the stupid mistakes I've made and seen others make.

This book is not a cookbook. Errors cannot be avoided by recipe. If they could, we could eliminate automobile accidents by plastering the countryside with "Drive Carefully" signs! People learn most effectively through experience--their own or someone else's. Merely understanding how a particular kind of mistake is possible is a big step on the way to avoiding it in the future.

This book is not intended to teach you how to program in C (see Kernighan and Ritchie: The C Programming Language, Second Edition, Prentice-Hall 1988), nor is it a reference manual (see Harbison and Steele: C: A Reference Manual, Second Edition, Prentice-Hall, 1987). It does not mention algorithms or data structures (see Van Wyk: Data Structures And C Programs, Addison-Wesley 1988), and only briefly discusses portability (see Horton: How To Write Portable Programs In C., Prentice-Hall 1989) and operating system interfaces (see Kernighan and Pike: The Unix Programming Environment, Prentice-Hall 1984). The problems mentioned are real, although often shortened (for a collection of composed C problems see Feuer: The C Puzzle Book, Prentice-Hall 1982). It is neither a dictionary nor an encyclopedia; I have kept it short to encourage you to read it all.

Your Name in Lights

I'm sure I've missed some pitfalls. If you find one I've missed, please contact me via Addison-Wesley. I may well include your discovery, with an acknowledgement, in a future edition.

A Word about ANSI C

As I write this, the ANSI C standard is not yet final. It is technically incorrect to refer to "ANSI C" until the ANSI committee finishes its work. In practice, though, the ANSI standard is far enough along that nothing I say about ANSI C is likely to change. C compilers are already available that implement many of the significant improvements contemplated by the ANSI committee.

Don't worry if your C implementation does not support the ANSI function syntax mentioned here: it is easy enough to understand the parts of the examples where it matters, and you can fall into the traps described there regardless of what version of C you use.

Acknowledgements

A collection like this could not possibly have been made in isolation. People who have pointed out particular pitfalls include Steve Bellovin, Mark Brader, Luca Cardelli, Larry Cipriani, Guy Harris and Steve Johnson, Phil Karn, Dave Kristol, George W. Leach, Doug McIlroy, Barbara Moo, Rob Pike, Jim Reeds, Dennis Ritchie, Janet Sirkis, Richard Stevens, Bjarne Stroustrup, Ephraim Vishnaic, and one contributor who wishes to remain anonymous. For brevity, I've mentioned only the first person to report any particular problem to me. Of course, I doubt any of the people I've mentioned actually invented the programming errors they pointed out to me, and if they did I doubt they'd admit it! I know I've made many of them myself too, some several times.

Useful 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 several anonymous reviewers. Lee McMahon and Ed Sitar pointed out what would otherwise have ben embarrassing typographical errors in early drafts of the manuscript. Dave Prosser clarified many fine points of ANSI C for me. Brian Kernighan supplied invaluable typesetting tools and assistance.

It has been a delight to work with the people at Addison-Wesley, including Jim DeWolf, Mary Dyer, Lorraine Ferrier, Katherine Harutunian, Marshall Henrichs, Debbie Lafferty, Keith Wollman, and Helen Wythe. I'm sure they've gained from the aid of others whom I haven't met.

I am particularly grateful to the enlightened managers at AT&T Bell Laboratories who made it possible for me to write this book at all, including Steve Chappell, Bob Factor, Wayne Hunt, Rob Murray, Will Smith, Dan Stanzione, and Eric Sumner.

The title of this book was suggested by Robert Sheckley's science-fiction anthology The People Trap and Other Pitfalls, Snares, Devices and Delusions (as well as Two Sniggles and a Contrivance), published by Dell Books in 1968.

0201179288P04062001

Updates

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020