The standard library: facilities and contracts
Choose library families, read buffer and error contracts, and distinguish hosted, freestanding, C17, C23, and platform facilities.
In this chapter9 sections
The standard library supplies common operations, from output to allocation and mathematical calculations. To use a function correctly, learn what its arguments mean, what it returns, and what the caller must provide. A familiar name alone is not enough.
1. Choose a family by the job
| Header | Main role |
|---|---|
<stdio.h> | Streams, formatted I/O, and file access |
<stdlib.h> | Allocation, numeric conversion, sorting, searching, and program termination |
<string.h> | Byte-region and null-terminated string operations |
<ctype.h> | Character classification and case conversion |
<math.h>, <fenv.h> | Mathematical functions and floating-point environment facilities |
<stddef.h>, <stdint.h>, <limits.h> | Common types, eligible integer types, and range information |
<assert.h>, <errno.h> | Assertion diagnostics and selected function error reporting |
<time.h>, <locale.h> | Time facilities and locale-dependent behavior |
Headers expose types, macros, and declarations; function implementations may be linked from a library, implemented by compiler builtins, or supplied another way. Include the specified header before using its facilities. Do not manually guess a prototype or assume one header will always include another for you. The table is a map of families, not an exhaustive header list.
2. Read the contract before the call
Ask: what are the argument types; which objects must exist; how much storage is readable or writable; may ranges overlap; who owns a returned pointer; and how is failure reported? These are part of correct use, not optional implementation details. For example, memcpy copies a known byte count between nonoverlapping valid regions; it does not discover a destination’s capacity.
char source[] = "C";
char destination[sizeof source];
memcpy(destination, source, sizeof source);
This fragment requires <string.h>. The array size includes the terminating null character, and the destination is a separate array of that exact size. Replacing the destination with a pointer to an unknown-capacity buffer would require a new capacity contract. Use memmove when the valid source and destination regions can overlap; it does not remove the requirement for sufficient storage.
3. Small interfaces can have precise argument rules
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
int main(void)
{
char letter = 'A';
int classification = isalpha((unsigned char)letter);
assert(classification != 0);
int input = EOF;
if (input != EOF) {
(void)isalpha(input);
}
return 0;
}
The <ctype.h> functions require EOF or a value representable as unsigned char. Converting a possibly negative plain char through unsigned char makes the argument suitable. A value read by getchar belongs in int until checked against EOF; casting first can lose the distinction. Classification returns zero or nonzero, not necessarily exactly one for true.
4. Learn each interface’s failure convention
malloc can return a null pointer; a file operation may report EOF, a short count, or an error indicator; strtol needs an end pointer and range checks. Some interfaces use errno, but C does not make it a universal last-error channel. Inspect it only under the documented rules for the operation, and save relevant error information before another call can change it.
Assertions express internal expectations and may be disabled by defining NDEBUG before including <assert.h>. Never put required input validation or required side effects only inside assert. The examples use assertions as checks in a learning build with assertions enabled. The later input unit develops actual validation and stream-error handling.
5. Hosted and freestanding implementations differ
A hosted implementation supplies the hosted execution environment and standard library, subject to standard feature conditions. A freestanding implementation has different startup and library requirements, useful for environments such as kernels or embedded systems. It is not simply a smaller executable, and embedded does not automatically mean freestanding.
C17’s minimum freestanding header set is <float.h>, <iso646.h>, <limits.h>, <stdalign.h>, <stdarg.h>, <stdbool.h>, <stddef.h>, <stdint.h>, and <stdnoreturn.h>. This does not guarantee hosted I/O or allocation. C17 also permits specified optional features to be absent, including threads and atomics; exact-width integer typedefs such as int32_t exist only when their requirements are met.
6. Distinguish standard C from platform additions
Sockets, directory traversal, operating-system threads outside the C threads interface, and graphical windows are not all guaranteed by the C standard library. POSIX, Windows, and third-party libraries define additional interfaces. They can be useful, but their availability and build instructions belong in an explicit platform contract. Even standard math functions may need a separate link option on a given toolchain.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 4p6–p7, 5.1.2, 7.1, 7.2, 7.4, 7.5, 7.20.1.1, 7.24.2. Stable core rules used for the C17 baseline; not the final ISO publication.
- WG14 N3096 — public C23 working draft: 4, 7.18, 7.20. C23 notes are separate from C17 example checks.
For focused explanations, continue to searching and sorting, dates and clocks, and floating-point math when their earlier prerequisites are familiar.
Before you move on
- Library facilities are organised by the jobs they support.
- Each call has argument, storage, result, and failure rules.
- Hosted, freestanding, optional, and platform-specific facilities have different availability contracts.
Keep these ideas separate
- Function signature / Complete contract
- The types do not automatically express capacities, overlap restrictions, ownership, or every valid argument range.
What would you check in a library function’s documentation before passing it a pointer and a count?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- Yes, the library repairs all invalid pointers.
A library interface does not remove the caller’s pointer and lifetime obligations.
- Yes, a header guarantees successful resource acquisition.
Operations such as allocation and file opening can still fail.
- No. The caller must also satisfy the function’s argument and state contracts.
✓ Correct reasoning. Bounds, formats, lifetimes, and error handling remain part of correct use.
C17
Quick reference from the earlier edition
Retained for existing section links and saved passages. The expanded explanation is above; documented corrections are recorded in the source review.
The C standard library is intentionally small compared to those of languages like Python or Java — a reflection of C's philosophy of providing only what is essential and leaving the rest to the programmer or to third-party libraries. Its functions fall into a handful of functional families:
- Input/Output (
stdio.h): theprintf/scanffamilies, character I/O (getchar,putchar), line I/O (fgets,fputs), and file operations (fopen,fclose,fread,fwrite). - String and Memory (
string.h): copying (strcpy,memcpy), concatenation (strcat), comparison (strcmp,memcmp), searching (strchr,strstr), and tokenizing (strtok). - General Utilities (
stdlib.h): dynamic memory (malloc,calloc,realloc,free), numeric conversions (atoi,atof,strtol), sorting and searching (qsort,bsearch), process control (exit,abort,system), and pseudo-random numbers (rand,srand). - Mathematics (
math.h): trigonometric, exponential, logarithmic, and rounding functions (sin,pow,sqrt,log,floor,ceil). - Character handling (
ctype.h): classification and case conversion such asisalpha,isdigit,toupper, andtolower. Arguments must beEOFor a value representable asunsigned char. For a possibly negative plainchar c, useisalpha((unsigned char)c); do not cast awayEOFbefore checking agetcharresult. - Date and Time (
time.h):time,clock,difftime,strftime. - Diagnostics (
assert.h,errno.h): runtime assertions and structured error reporting.
Later sections revisit several of these families — dynamic memory (Section 22), formatted I/O (Section 23), and file handling (Section 24) — in much greater depth.
Ready for the next idea?
Mark this chapter as read whenever you feel ready.