4.9 Input/Output ANSI C Rationale 4.11 String Handling              Index

# 4.10General 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.1The `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.

See §4.10.1.1

See §4.10.1.1

## 4.10.1.4The `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.

See §4.10.1.4

## 4.10.1.6The `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.1The `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.

## 4.10.3Memory 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.

QUIET CHANGE

A program which relies on size-0 allocation requests returning a non-null pointer will behave differently.
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.

## 4.10.3.1The `calloc` function

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

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.

## 4.10.3.2The `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.

## 4.10.3.4The `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.1The `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.

## 4.10.4.2The `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.

## 4.10.4.3The `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`).

## 4.10.4.4The `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.

## 4.10.4.5The `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.6Integer 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.

## 4.10.6.1The `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.

## 4.10.6.2The `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
```
Table 4.2: Results of `div` and `ldiv`
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.

## 4.10.7Multibyte character functions

See §2.2.1.2 for an overall discussion of multibyte character representations and wide characters.

## 4.10.8Multibyte string functions

See §2.2.1.2 for an overall discussion of multibyte character representations and wide characters.

## 4.10.8.2The `wcstombs` function

4.9 Input/Output ANSI C Rationale 4.11 String Handling              Index