Chapter 16 of 24
16. The C standard library
Use the tools C already provides
The C standard library is a collection of functions and types that a conforming C implementation provides. It offers common building blocks so you do not have to write every basic operation yourself.
- Identify the task, such as printing text, measuring a string, or allocating memory.
- Find the standard header that declares the needed function, then include it.
- Read the function's contract: what arguments it expects, what it returns, and how it reports failure.
Use a library function only when its input and result rules fit your situation. This chapter groups useful facilities by task and shows how to check their results.
The standard library provides portable functions and types. Learn these
headers as you need them:
<stdio.h>: streams and formatted input/output.<stdlib.h>: allocation, conversions, process control, and sorting/searching
utilities.<string.h>: byte and string operations.<ctype.h>: character classification and conversion. Pass eitherEOFor
a value representable asunsigned charto its functions.<math.h>: mathematical functions; some toolchains require linking a math
library separately.<stdint.h>,<inttypes.h>: integer types and format macros.<stdbool.h>: Boolean names in C17.<stddef.h>: common definitions such assize_tandNULL.<errno.h>: error-reporting conventions used by some library functions.<time.h>: time and date facilities.<assert.h>: development-time assertions.<limits.h>,<float.h>: implementation limits.
Read each function's documentation for its valid inputs, return values, and
failure behavior. Check return values where failure is possible.
Learning the library by task
Do not try to memorize every library function. Start from the operation you
need, select the appropriate header, and check its documentation for:
parameter types, valid input ranges, return-value meaning, error reporting,
and ownership of any returned storage.
For example, <string.h> contains both string functions that expect a null
terminator and byte-oriented functions that use an explicit byte count. These
are not interchangeable: strlen needs a valid string, while memcpy
copies a specified number of bytes and requires non-overlapping regions.
qsort can sort arrays of many element types but requires a correctly written
comparison function and the right element size.
Functions in <ctype.h> accept EOF or values representable as
unsigned char. If a plain char may be negative, convert it before calling
a classification function:
#include <ctype.h>
#include <stdio.h>
int main(void)
{
char character = ' ';
if (isspace((unsigned char)character)) {
puts("Whitespace");
}
return 0;
}
The standard library is portable, but system calls and compiler-specific
libraries are not necessarily so. When a function is not part of standard C,
identify the platform or library that provides it.
Checkpoint: Before using a library function, find its header, required
argument types, return-value rules, and whether it can fail.
Common library facilities in practice
<stdlib.h>providesstrtol,strtod,malloc,free,qsort, and
EXIT_SUCCESS/EXIT_FAILURE. For conversions, check whether any characters
were consumed, whether the value was in range, and whether trailing text is
permitted.<string.h>provides string and byte operations. String functions require
valid terminators; memory functions use explicit byte counts.<math.h>provides functions such assqrt,pow,sin, andisfinite.
Check domain and range requirements and link any platform-specific math
library when the toolchain requires it.<time.h>provides calendar and clock interfaces with implementation
limits; it is not automatically a high-resolution benchmark facility.<assert.h>checks internal invariants during development but should not
replace validation of user input.<errno.h>is meaningful only for functions that document setting it.
Clear it before a conversion when appropriate and inspect it only according
to that function's contract.
The library's return value is often more reliable than assumptions about
global error state. Read the function documentation and inspect the result
first; use errno only when the function's specification says to.
qsort accepts a comparator callback. The comparator must return a negative
value when the first element sorts before the second, zero when they compare
equal, and a positive value when the first sorts after the second. Do not
subtract values to produce the result: subtraction can overflow.
int compare_ints(const void *left, const void *right)
{
const int *a = left;
const int *b = right;
return (*a > *b) - (*a < *b);
}
Call it with the base pointer, element count, element size, and comparator:
qsort(values, length, sizeof values[0], compare_ints);. The function sorts
the array in place and does not promise a stable order for equal elements.
#include <inttypes.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
int main(void)
{
int32_t count = 9;
double root = sqrt((double)count);
printf("count=%" PRId32 ", square root=%.1f\n", count, root);
return isfinite(root) ? 0 : 1;
}
PRId32 from <inttypes.h> supplies the correct format for int32_t.
Some toolchains require a separate math-library link option for sqrt.