Chapter 18: Standard Library Reference
The C Standard Library is a collection of headers and functions that provide essential services like memory management, mathematical calculations, and string manipulation. Mastering these headers is key to writing idiomatic and efficient C code.
I. Core Runtime Headers
1. <stdio.h> (Input and Output)
The most used header. Provides functions for reading from and writing to files and standard streams.
printf,scanf,fopen,fclose,fgets,fputs.
2. <stdlib.h> (General Utilities)
Provides memory management, process control, and conversions.
malloc,free,exit,rand,srand,abs,atoi(string to int).
3. <string.h> (String Manipulation)
Essential for handling C-style (null-terminated) strings.
strlen,strcpy,strcat,strcmp,memset(set memory),memcpy(copy memory).
II. System and Type Headers
4. <stdint.h> (Fixed-width Integers)
Crucial for portable code. Defines types with exact bit widths.
int8_t,uint32_t,intptr_t.
5. <stddef.h> (Standard Definitions)
Defines common types and macros used throughout the language.
size_t(unsigned integer for sizes),NULL,offsetof(offset of a member in a struct).
6. <stdbool.h> (Boolean Type)
Introduced in C99. Defines bool, true (1), and false (0).
III. Mathematical and Diagnostic Headers
7. <math.h> (Common Mathematics)
Advanced math operations. Needs to be linked with -lm.
sqrt,pow,log,sin,cos.
8. <errno.h> (Error Numbers)
Defines the errno global variable and various error codes (e.g., EACCES, ENOMEM) set by system calls.
9. <assert.h> (Diagnostics)
Provides the assert() macro for verifying assumptions during debugging.
assert(x > 0);(Aborts the program if x is not greater than 0).
IV. The time.h Library
Used for handling date and time.
time(): Returns the number of seconds since the Unix Epoch (Jan 1, 1970).localtime(): Converts atime_tto a struct containing hours, minutes, etc.
V. Advanced: <setjmp.h> and <signal.h>
setjmp.h: Provides a way to perform "non-local jumps"—effectively an early version of exception handling.signal.h: Allows your program to handle OS-level signals (likeSIGINTwhen the user pressesCtrl+C).
VI. Implementation Variations (glibc vs. musl)
While the headers are standard, their underlying implementation can vary. glibc (GNU C Library) is the standard for most Linux distributions, while musl is a lightweight alternative often used in Docker images and embedded systems.