Monday, January 14, 2008

Top Ten, 18 of 10

When we last left our hero, we were looking at ten ways to get screwed by the "C" programming language. Today's entry is Fabulously awful "standard libraries"

It turns out that libraries are harder to write than C compilers. Now, designing a good language may be difficult. But implementing an already standard language is a matter of meeting the requirements. Libraries are generally not written to standards. One writes a library by one of two processes. Either one has a task to do, and builds a library to support that task while building an application. Or, one tries to guess what functions programmers might need, and provides functions that do those things. Both approaches have problems. Your application might not need something other programmers will need. Your application might need the same things, but with peculiar semantics, making the implementation difficult to use. Or, you might not have guessed what other programmers might need. C's standard library isn't worse than most. There were a few mistakes, such as scanf(3), and index(3). There were some omissions in the original version, like strstr(3). While the bugs that were designed in are still there, for backward compatibility, solutions to those problems are available. One is told to use the fixed versions. Don't use scanf(3) - use fgets(3), then sscanf(3). Don't use index(3), use the new name strchr(3). I count the standard C library as a success because i actually use it, and don't invent a new string library. At least scanf(3) has a good excuse. The idea was to allow string parsing to work on streams. It's just that scanf(3) isn't a good way to make that happen. That said, i have written a stream based parser that needed it's own version of atof(3). That's about it.

1 comment:

Stephen said...

One of the changes i might have made to the C library is in strcat(). i'd have been very tempted to have strcat() return the location of the null character that was placed in the destination string. Then multiple strcat() calls would not need to first search for the end of the string before adding a new string. It's an optimization.

Is this a big deal? Probably not. In fact, i don't use strcat() very often, since i often feel the need to first check if the destination is large enough to place the expanded string. And, i don't like to use strncat(), since it doesn't guarantee that the string will be null terminated. These warts in the C library are being addressed in updates to the language standard. Existing code won't automagically be fixed. Programmers will need to get up to speed on it. Of these two, i suspect that programmer training is the harder issue to fix. There is no easy way to get the word out to everyone.