Expert C Programming

(Jeff_L) #1

my HP/IBM/PC." They want printf to print the empty string when given a null pointer.


The problem is that the C standard lays down that the argument for a %s specifier shall be a
pointer to an array of characters. Since NULL is not such a pointer (it's a pointer, but not to
an array of characters), the call falls into "undefined behavior."


Since the programmer has coded something wrongly, the question is, "At what point do you
wish to bring this to his or her attention?" If you insist that printf should handle a null
pointer as though it were valid, which other routines in libc should also do this? What
should strcmp() do if one of its arguments is null? Do you want to let printf helpfully do
what it thinks the programmer meant (likely allowing the program to run into bigger trouble
later on), or do you want to check the program at the earliest available point?


The Sun libc chooses the second of these alternatives. Other libc vendors have chosen the
first which, while arguably friendlier, is also less safe. There is also the question of
consistency. Which other routines in libc are you going to extend by allowing null pointers?


Using Pointers to Create and Use Dynamic Arrays


Programmers use dynamic arrays when we don't know the size of the data in advance. Most languages
that have arrays also provide the ability to set their size at runtime. They allow the programmer to
calculate the number of things to be processed, then create an array just big enough to hold them all.
Historic languages like Algol-60, PL/I, and Algol-68 permitted this. Newer languages like Ada,
Fortran 90, and GNU C (the language implemented by the GNU C compiler) also let you declare
arrays the size of which is set at runtime.


However, arrays are static in ANSI C—the size of an array is fixed at compiletime. C is so poorly
supported in this area that you can't even use a constant like this:


const int limit=100;


char plum[limit];


^^^


error: integral constant expression expected


We won't ask embarrassing questions about why a const int isn't regarded as being an integral
constant expression. The statement is legal in C++, for example.


It would have been easy to introduce dynamic arrays with ANSI C, since the necessary "prior art" was
there. All that would be needed is to change the line in Section 5.5.4 from


direct-declarator [constant-expression (^) opt]


to


direct-declarator [expression (^) opt]
It would actually have simplified the definition by removing an artificial restriction. The language
would still have been compatible with K&R C, and it would have provided some useful functionality.
Because of the strong desire to adhere to the original simple design goals of C, this was not done.

Free download pdf