4.9 Input/Output  -< ANSI C Rationale  -> 4.11 String Handling              Index 

4.10  General Utilities  <stdlib.h>

The header <stdlib.h> was invented by the Committee to hold an assortment of functions that were otherwise homeless. 

4.10.1  String conversion functions  The atof function

atof, atoi, and atol are subsumed by strtod and strtol, but have been retained because they are used extensively in existing code.  They are less reliable, but may be faster if the argument is known to be in a valid range.  The atoi function

See §  The atol function

See §  The strtod function

strtod and strtol have been adopted (from UNIX System V) because they offer more control over the conversion process, and because they are required not to produce unexpected results on overflow during conversion.  The strtol function

See §  The strtoul function

strtoul was introduced by the Committee to provide a facility like strtol for unsigned long values.  Simply using strtol in such cases could result in overflow upon conversion. 

4.10.2  Pseudo-random sequence generation functions  The rand function

The Committee decided that an implementation should be allowed to provide a rand function which generates the best random sequence possible in that implementation, and therefore mandated no standard algorithm.  It recognized the value, however, of being able to generate the same pseudo-random sequence in different implementations, and so it has published as an example in the Standard an algorithm that generates the same pseudo-random sequence in any conforming implementation, given the same seed.  The srand function

4.10.3  Memory management functions

The treatment of null pointers and 0-length allocation requests in the definition of these functions was in part guided by a desire to support this paradigm:
        OBJ * p; /* pointer to a variable list of OBJ's */

        /* initial allocation */
        p = (OBJ *) calloc(0, sizeof(OBJ));
        /* ... */

        /* reallocations until size settles */
        while(/* list changes size to c */) {
            p = (OBJ *) realloc((void *)p, c*sizeof(OBJ));
            /* ... */
This coding style, not necessarily endorsed by the Committee, is reported to be in widespread use. 

Some implementations have returned non-null values for allocation requests of 0 bytes.  Although this strategy has the theoretical advantage of distinguishing between ``nothing'' and ``zero''  (an unallocated pointer vs. a pointer to zero-length space), it has the more compelling theoretical disadvantage of requiring the concept of a zero-length object.  Since such objects cannot be declared, the only way they could come into existence would be through such allocation requests.  The Committee has decided not to accept the idea of zero-length objects.  The allocation functions may therefore return a null pointer for an allocation request of zero bytes.  Note that this treatment does not preclude the paradigm outlined above. 

Some implementations provide a function (often called alloca which allocates the requested object from automatic storage; the object is automatically freed when the calling function exits.  Such a function is not efficiently implementable in a variety of environments, so it was not adopted in the Standard.  The calloc function

Both nelem and elsize must be of type size_t, for reasons similar to those for fread (see § 

If a scalar with all bits zero is not interpreted as a zero value by an implementation, then calloc may have astonishing results in existing programs transported there.  The free function

The Standard makes clear that a program may only free that which has been allocated, that an allocation may only be freed once, and that a region may not be accessed once it is freed.  Some implementations allow more dangerous license.  The null pointer is specified as a valid argument to this function to reduce the need for special-case coding.  The malloc function  The realloc function

A null first argument is permissible.  If the first argument is not null, and the second argument is 0, then the call frees the memory pointed to by the first argument, and a null argument may be returned; this specification is consistent with the policy of not allowing zero-size objects. 

4.10.4  Communication with the environment  The abort function

The Committee vacillated over whether a call to abort should return if the signal SIGABRT is caught or ignored.  To minimize astonishment, the final decision was that abort never returns.  The atexit function

atexit provides a program with a convenient way to clean up the environment before it exits.  It is adapted from the Whitesmiths C run-time library function onexit

A suggested alternative was to use the SIGTERM facility of the signal/raise machinery, but that would not give the last-in first-out stacking of multiple functions so useful with atexit

It is the responsibility of the library to maintain the chain of registered functions so that they are invoked in the correct sequence upon program exit.  The exit function

The argument to exit is a status indication returned to the invoking environment.  In the UNIX operating system, a value of 0 is the successful return code from a program.  As usage of C has spread beyond UNIX, exit(0) has often been retained as an idiom indicating successful termination, even on operating systems with different systems of return codes.  This usage is thus recognized as standard.  There has never been a portable way of indicating a non-successful termination, since the arguments to exit are then implementation-defined.  The macro EXIT_FAILURE has been added to provide such a capability.  (EXIT_SUCCESS has been added as well.) 

Aside from calls explicitly coded by a programmer, exit is invoked on return from main Thus in at least this case, the body of exit cannot assume the existence of any objects with automatic storage duration (except those declared in exit).  The getenv function

The definition of getenv is designed to accommodate both implementations that have all in-memory read-only environment strings and those that may have to read an environment string into a static buffer.  Hence the pointer returned by the getenv function points to a string not modifiable by the caller.  If an attempt is made to change this string, the behavior of future calls to getenv is undefined.

A corresponding putenv function was omitted from the Standard, since its utility outside a multi-process environment is questionable, and since its definition is properly the domain of an operating system standard.  The system function

The system function allows a program to suspend its execution temporarily in order to run another program to completion. 

Information may be passed to the called program in three ways: through command-line argument strings, through the environment, and (most portably) through data files.  Before calling the system function, the calling program should close all such data files. 

Information may be returned from the called program in two ways: through the implementation-defined return value (in many implementations, the termination status code which is the argument to the exit function is returned by the implementation to the caller as the value returned by the system function), and (most portably) through data files. 

If the environment is interactive, information may also be exchanged with users of interactive devices. 

Some implementations offer built-in programs called ``commands''  (for example, ``date'')  which may provide useful information to an application program via the system function.  The Standard does not attempt to characterize such commands, and their use is not portable. 

On the other hand, the use of the system function is portable, provided the implementation supports the capability.  The Standard permits the application to ascertain this by calling the system function with a null pointer argument.  Whether more levels of nesting are supported can also be ascertained this way; assuming more than one such level is obviously dangerous. 

4.10.5  Searching and sorting utilities  The bsearch function  The qsort function

4.10.6  Integer arithmetic functions

abs was moved from <math.h> as it was the only function in that library which did not involve double arithmetic.  Some programs have included <math.h> solely to gain access to abs, but in some implementations this results in unused floating-point run-time routines becoming part of the translated program.  The abs function

The Committee rejected proposals to add an absolute value operator to the language.  An implementation can provide a built-in function for efficiency.  The div function

div and ldiv provide a well-specified semantics for signed integral division and remainder operations.  The semantics were adopted to be the same as in FORTRAN Since these functions return both the quotient and the remainder, they also serve as a convenient way of efficiently modelling underlying hardware that computes both results as part of the same operation.  Table 4.2 summarizes the semantics of these functions.

        numer   denom    quot     rem
          7       3      2       1
         -7       3     -2      -1
          7      -3     -2       1
         -7      -3      2      -1
Divide-by-zero is described as undefined behavior rather than as setting errno to EDOM The program can as easily check for a zero divisor before a division as for an error code afterwards, and the adopted scheme reduces the burden on the function.  The labs function  The ldiv function

4.10.7  Multibyte character functions

See § for an overall discussion of multibyte character representations and wide characters.  The mblen function  The mbtowc function  The wctomb function

4.10.8  Multibyte string functions

See § for an overall discussion of multibyte character representations and wide characters.  The mbstowcs function  The wcstombs function

4.9 Input/Output  -< ANSI C Rationale  -> 4.11 String Handling              Index