YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Building programsChapter 44 of 73

The standard library: facilities and contracts

Choose library families, read buffer and error contracts, and distinguish hosted, freestanding, C17, C23, and platform facilities.

6 min readIntermediateC17 baseline
Offline reading
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

HeaderMain 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.

C17 · illustrative fragment
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

Complete C17 program
#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

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.
Explain it in your own words

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.

Does a valid library declaration make every call valid?
Read the explanation for every choice
  1. Yes, the library repairs all invalid pointers.

    A library interface does not remove the caller’s pointer and lifetime obligations.

  2. Yes, a header guarantees successful resource acquisition.

    Operations such as allocation and file opening can still fail.

  3. 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): the printf/scanf families, 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 as isalpha, isdigit, toupper, and tolower. Arguments must be EOF or a value representable as unsigned char. For a possibly negative plain char c, use isalpha((unsigned char)c); do not cast away EOF before checking a getchar result.
  • 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.

CHAPTER 44 / 73

In this chapter

The standard library: facilities and contracts

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping