C Library – <stdlib.h>

The ANSI C standard library includes a variety of utility functions defined in stdlib.h. The header file defines the types shown in table below:

Type Description
size_t The integer type returned by the sizeof operator.
wchar_t The integer type used to represent wide characters.
div_t The structure type returned by div(); it has a quot and a rem member, both of type int.
ldiv_t The structure type returned by ldiv(); it has a quot and a rem member, both of type long.

The header file defines the constants listed in table below:

Type Description
NULL The null pointer (equivalent to 0).
EXIT_FAILURE Can be used as an argument to exit() to indicate unsuccessful execution of a program.
EXIT_SUCCESS Can be used as an argument to exit() to indicate successful execution of a program.
RAND_MAX The maximum value (an integer) returned by rand().
MB_CUR_MAX The maximum number of bytes for a multibyte character for the extended character set corresponding to the current locale.

Table below lists the functions whose prototypes are found in stdlib.h.

Prototype Description
double atof(const char * nptr); Returns the initial portion of the string nptr converted to a type double value; conversion ends upon reaching the first character that is not part of the number; initial whitespace is skipped; zero is returned if no number is found.
int atoi(const char * nptr); Returns the initial portion of the string nptr converted to a type int value; conversion ends upon reaching the first character that is not part of the number; initial whitespace is skipped; zero is returned if no number is found.
int atol(const char * nptr); Returns the initial portion of the string nptr converted to a type long value; conversion ends upon reaching the first character that is not part of the number; initial whitespace is skipped; zero is returned if no number is found.
double strtod(const char * npt, char **ept); Returns the initial portion of the string nptr converted to a type double value; conversion ends upon reaching the first character that is not part of the number; initial whitespace is skipped; zero is returned if no number is found; if conversion is successful, the address of the first character after the number is assigned to the location pointed to by ept; if conversion fails, npt is assigned to the location pointed to by ept.
long strtol(const char * npt, char **ept, int base); Returns the initial portion of the string nptr converted to a type long value; conversion ends upon reaching the first character that is not part of the number; initial whitespace is skipped; zero is returned if no number is found; if conversion is successful, the address of the first character after the number is assigned to the location pointed to by ept; if conversion fails, npt is assigned to the location pointed to by ept; the number in the string is assumed to be written in a base specified by base.
unsigned long strtoul(const char * npt, char **ept, int base); Returns the initial portion of the string nptr converted to a type unsigned long value; conversion ends upon reaching the first character that is not part of the number; initial whitespace is skipped; zero is returned if no number is found; if conversion is successful, the address of the first character after the number is assigned to the location pointed to by ept; if conversion fails, npt is assigned to the location pointed to by ept; the number in the string is assumed to be written in a base specified by base.
int rand(void); Returns a pseudorandom integer in the range 0 to RAND_MAX.
void srand(unsigned int seed); Sets the random-number generator seed to seed; if rand() is called before a call to srand(), the seed is 1.
void *calloc(size_t nmem, size_t size); Allocates space for an array of nmem members, each element of which is sizebytes in size; all bits in the space are initialized to 0; the function returns the address of the array if successful, and NULL otherwise.
void free(void *ptr); Deallocates the space pointed to by ptr; ptr should be a value previously returned by a call to calloc(), malloc(), or realloc(), or ptr can be the null pointer, in which case no action is taken; the behavior is undefined for other pointer values.
void *malloc(size_t size); Allocates an uninitialized block of memory of size bytes; the function returns the address of the array if successful, and NULL otherwise.
void *realloc(void *ptr, size_t size); Changes the size of the block of memory pointed to by ptr to size bytes; the contents of the block up to the lesser of the old and new sizes are unaltered; the function returns the location of block, which may have been moved; if space cannot be reallocated, the function returns NULL and leaves the original block unchanged; if ptr is NULL, the behavior is the same as calling malloc()with an argument of size; if size is zero and ptr is not NULL, the behavior is the same as calling free() with ptr as an argument.
void abort(void); Causes abnormal program termination unless the signal SIGABRT is caught and the corresponding signal handler does not return; closing of I/O streams and temporary files is implementation-dependent; the function executes raise(SIGABRT).
int atexit(void (*func)(void)); Registers the function pointed to by func to be called upon normal program termination; the implementation should support registration of at least 32 functions, which will be called opposite the order in which they are registered; the function returns zero if registration succeeds, and non-zero otherwise.
void exit(int status); Causes normal program termination to occur, first invoking the functions registered by atexit(), then flushing all open output streams, then closing all I/O streams, then closing all files created by tmpfile(), and then returning control to the host environment; if status is 0 or EXIT_SUCCESS, an implementation-defined value indicating successful termination is returned to the host environment; if status is EXIT_FAILURE, an implementation-defined value indicating unsuccessful termination is returned to the host environment; the effect of other values of status is implementation-defined.
char *getenv(const char * name); Returns a pointer to a string representing the value of the environmental variable pointed to by name; returns NULL if it cannot match the specified name.
int system(const char *str); Passes the string pointed to by str to the host environment to be executed by a command processor, such as DOS or UNIX; if str is the NULL pointer, the function returns non-zero if a command processor is available, and zero otherwise; if str is not NULL, the return value is implementation-dependent.
void *bsearch(const void *key, const void *base, size_t nmem, size_t size, int (*comp)(const void *, const void *)); Searches an array pointed to by base having nmem members of size size for an element matching the object pointed to by key; items are compared by the function pointed to by comp; the comparison function shall return a value less than zero if the key object is less than an array element, zero if they are equivalent, and more if the key object is greater; the function returns a pointer to a matching element, or NULL if no element matches; if two or more elements match the key, it is unspecified which of the matching elements will be selected.
void qsort(void *base, size_t nmem, size_t size, int (*comp) (const void *, const void *)); Sorts the array pointed to by base in the order provided by the function pointed to by comp; the array has nmem elements each of size bytes; the comparison function shall return a value less than zero if the object pointed to by the first argument is less than the object pointed to by the second argument, zero if the objects are equivalent, and more if the first object is greater.
int abs(int n); Returns the absolute value of n; the return value may be undefined if n is a negative value with no positive counterpart, which can happen if n is INT_MINin two’s complement representation.
div_t div(int numer, int denom); Computes the quotient and remainder from dividing numer by denom, placing the quotient in the quot member of a div_t structure and the remainder in the rem member; for inexact division, the quotient is the integer of lesser magnitude that is nearest the algebraic quotient (that is, truncate toward zero).
long labs(int n); Returns the absolute value of n; the return value may be undefined if n is a negative value with no positive counterpart, which can happen if n is LONG_MINin two’s complement representation.
ldiv_t ldiv(long numer, long denom); Computes the quotient and remainder from dividing numer by denom, placing the quotient in the quot member of a ldiv_t structure and the remainder in the rem member; for inexact division, the quotient is the integer of lesser magnitude that is nearest the algebraic quotient (that is, truncate toward zero).
int mblen(const char *s, size_t n); Returns the number of bytes (up to n) constituting the multibyte character pointed to by s, returns 0 if s points to the null character, returns -1 if s does not point to a multibyte character; if s is NULL, returns non-zero if multibyte characters have state-dependent encoding, and zero otherwise.
int mbtowc(wchar_t *pw, const char *s, size_t n); If s is not NULL, determines the number of bytes (up to n) constituting the multibyte character pointed to by s and determines the type wchar_t code for that character; if pw is not NULL, assigns the code to the location pointed to be pw; returns the same value as mblen(s, n).
int wctomb(char *s, wchar_t wc); Converts the character code in wc to the corresponding multibyte character representation and stores it in the array pointed to by s, unless s is NULL; if s is not NULL, returns -1 if wc does not correspond to a valid multibyte chararacter or, if wc is valid, the number of bytes constituting the multibyte character; if sis NULL, returns non-zero if multibyte characters have state-dependent encoding, and zero otherwise.
size_t mbstowcs(wchar_t *pwcs, const char *s, size_t n); Converts the array of multibyte characters pointed to by s to an array of wide character codes stored at the location beginning at pwcs; conversion proceeds up to n elements in the pwcs array or a null byte in the s array, whichever occurs first; if an invalid multibyte character is encountered, returns (size_t) (-1); otherwise, returns the number of array elements filled (excluding a null character, if any).
size_t wcstombs(char *s, const wchart_t *pwcs, size_t n); Converts the sequence of wide-character codes stored in the array pointed to by pwcs into a multibyte character sequence copied to the location pointed to by s, stopping after storing n bytes or a null character, whichever comes first; if an invalid wide character code is encountered, returns (size_t) (-1); otherwise, returns the number of array bytes filled (excluding a null character, if any).

Often seen as a collection point for all the miscellaneous functionality that seems to fit nowhere else, the stdlib contains many interesting features for a variety of applications.

You previously used the return keyword in the main function to leave the program itself; however, stdlib also offers some additional exit handling that extends this behavior. The first, atexit, is defined as:

atexit ( <function> )          // execute function on exit

This function allows you to specify up to 32 functions (in separate calls to atexit) to execute when the program terminates normally. These functions cannot accept any parameters and will be executed in the reverse order to which they were set up by repeated calls to the atexit function.

To stop the program immediately due to an unrecoverable error being encountered, you use the abort function. It is defined, quite simply, as:

abort      ( )             // stop the program

When the program exits, the message Abnormal Program Termination is printed and exit code 3 set. To forcefully end the program without causing the effects of a call to abort, you use the exit function. This function is defined as:

exit ( <0 or 1> )       // exit the program, returning 0 or 1

Generally speaking, 0 is used to signal normal program termination (to the operating system), whereas 1 is used to signify an abnormal program termination. The key difference between exit and abort is that exit will call any functions set up with calls to atexit, whereas abort will not.

In order to return a specific code to the operating system, it is necessary to use the return keyword. The drawback is that the operating system must check the return value against a list to determine whether the program has completed successfully. The two termination functions allow you to indicate this, but without a specific return code.

One piece of functionality that might have been left in the math library but has instead been included in stdlib is used to generate a stream of pseudorandom numbers. A pseudorandom number sequence is one that has no immediately discernable pattern, but that will eventually repeat over time since it is created using a static algorithm.

To prepare the algorithm, a seed is required, which is a number used in the first iteration of the algorithm. As a consequence, if the same seed value is used every time the algorithm is used, the same sequence of pseudorandom numbers will ensue. The seed function is defined as:

srand ( <seed value> )    // seed the random number generator

The seed value is a long integer. Commonly used values include the current system time (in clock ticks). For a full discussion of the time functions available in the Time library, see the next section. Seeding with the time function can be done as follows:

srand ( time ( NULL ) );

The function does not return a value. To obtain the next pseudorandom number in the sequence, the rand function is used, and defined as:

rand ( )   // returns a random value

The compiler environment will probably have set a constant RAND_MAX, which is usually set to 32,767. This means that the function will return a number between 0 and 32,767. You can obtain a number with an arbitrary maximum by using the modulo % operator:

int nMyRandomNumber;
nMyRandomNumber = rand ( ) % nMyMax;

This code will return a value between 0 and whatever nMyMax is set to. Repeated calls to rand will result in a sequence of different numbers, but the sequence will repeat after a large number of calls.

Two other functions might have been included elsewhere but are usually also defined in stdlib handle string-to-number conversions. You can convert from strings to floating-point or integer values using the following two functions:

atof ( <string> )     // returns floating-point from string
atoll ( <string> )    // returns integer from string

These functions take a string and return either a floating-point or integer conversion. Various options are supported, including correct translation of signed values.

A very useful but slightly advanced function called qsort is provided to help sort arrays of information. Before reading the following, please note that it may benefit you if you’re new to programming to read Chapter 10, “User-Defined Functions,” first and come back to this discussion afterwards. I provide it here for completeness and ease of reference.

Before using qsort, a comparison function needs to be set up, which receives two elements and returns -1 if the first element goes before the second one, 0 if they are both equal, and 1 if the first element goes after the second element.

The function must be user defined, with parameters that have data types that match the expected input data types. These can, however, be built-in or user-defined data types, including complex data types such as structures.

In addition, you need a pointer to the first element in the array (or memory block), the number of items in the array, and the width (size) of each element. The function cannot therefore be used to sort variable-width items. The definition of qsort looks like:

qsort ( <pointer>, <items>, <size>,
     <compare function> )

<pointer> is the pointer to memory block or array, is the number of items to be sorted, and <compare function> takes two elements of the same data type. If you want to sort a memory block of 100 integers, you should first set up a comparison function.

Related Post