Chapter 13. Errors When Using Standard C Libraries

As we discussed in Chapter 1, C++ inherited the C philosophy and its corresponding problems. But that’s not all. It also inherited the standard C library, which is unsafe in several ways, and consequently all its associated problems, sometimes leading to unpredictable behavior up to and including program crashes. For the final chapter in this part of the book, we’ll discuss the possible dangers that await you when you use some of the functions that programmers frequently depend on in these libraries.

When we try to use the C string libraries declared in string.h or functions such as sprintf() declared in stdio.h, we may face the following problems:

  • The functions that take pointers to character arrays (char *) crash when given a NULL instead of a pointer to a valid C string (for example, strlen(NULL) will crash).

  • Some of the functions writing into a buffer might overwrite past the end of the buffer, thus leading to unpredictable application behavior including crashes.

  • The safer versions of the same functions will not overwrite the buffer, but will stop writing into a buffer just before it ends, thus silently truncating the result—probably not the behavior one would want.

There are several potential ways to address these problems:

  • Provide versions of the functions that do all the necessary sanity checks and treat the NULL pointers the same way as they would handle an empty string (const char* empty_string = "";).

  • For those applications ...

Get Safe C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.