C stdlib.h Tutorial

What stdlib.h Covers
<stdlib.h> is C's general-utilities header. It is not one narrow subsystem: it brings together dynamic memory, text-to-number conversion, program termination, environment lookup, generic sorting and searching, pseudo-random sequences, integer arithmetic helpers, and locale-aware multibyte conversion.
Beginners usually meet it through malloc(), free(), and atoi(). The safer path is to learn each function as a contract: who owns memory, which inputs are valid, what indicates failure, and which side effects occur.
malloc() and free(): One Owner, One Release
malloc() requests raw, uninitialized storage. It returns a pointer when successful and NULL when the request cannot be satisfied. The allocation is not tied to the scope that created it; its lifetime ends only when free() receives the original live allocation pointer.
Write down the ownership rule in your design. The owner checks allocation, initializes before reading, transfers ownership only deliberately, and releases exactly once. Never use a pointer after its allocation has been freed.
| Function | Use | Beginner check |
|---|---|---|
malloc(size) | Uninitialized bytes | Check NULL; initialize before reading. |
calloc(count, size) | Zero-filled bytes for an array | Check NULL; remember byte-zero nuance. |
realloc(ptr, size) | Resize an existing block | Assign to a temporary pointer first. |
aligned_alloc(a, size) | Explicitly aligned block | Make size a multiple of alignment. |
free(ptr) | End allocation lifetime | Free once; NULL is harmless. |
atoi() vs strtol()
atoi() is short, but it cannot tell you whether 0 came from valid text, missing digits, or a conversion problem. It also does not expose trailing text or a dependable range error. That makes it a poor fit for configuration, command-line arguments, files, network data, and other untrusted input.
strtol() gives you an end pointer and uses errno for range failure. A robust check resets errno, requires at least one digit, decides whether trailing characters are allowed, and verifies the destination range if narrowing to int.
| Question | atoi() | strtol() |
|---|---|---|
| Were any digits consumed? | Cannot tell reliably | Check end != text |
| Where did parsing stop? | Not available | Inspect *end |
| Was long range exceeded? | No dependable report | Check errno == ERANGE |
| Can base prefixes be detected? | Decimal only | Pass base 0 |
atoi() only when the text is already guaranteed valid and in range. Prefer strtol() for untrusted input.Starter Example: Parse, Allocate, Use, Free
This program combines two central stdlib.h skills: checked conversion and explicit memory ownership.
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const char *text = "4";
char *end;
errno = 0;
long count = strtol(text, &end, 10);
if (end == text || *end != '\0' || errno == ERANGE ||
count < 1 || count > INT_MAX) {
puts("invalid count");
return EXIT_FAILURE;
}
int *values = malloc((size_t)count * sizeof *values);
if (values == NULL) {
puts("allocation failed");
return EXIT_FAILURE;
}
for (long i = 0; i < count; ++i)
values[i] = (int)(i + 1) * 10;
printf("first = %d, last = %d\n", values[0], values[count - 1]);
free(values);
return EXIT_SUCCESS;
}How It Works
- Parse with evidence.
strtol()reports where conversion stops, whileerrnoreports range failure. - Validate the intended domain. The program requires a positive value that can fit the later loop and indexing design.
- Allocate by element type. The byte count uses
sizeof *values, and NULL is checked before writing. - End ownership once. After the final read,
free(values)releases the block exactly once.
Find the Right Family
Process control
Terminate programs, register cleanup work, or invoke the host command processor.
abort(), exit(), _Exit(), quick_exit(), atexit(), at_quick_exit(), system()
Memory
Create, resize, align, and release dynamic storage with explicit ownership.
Integer absolute value and division
Compute magnitudes or quotient-and-remainder pairs for standard integer widths.
String to number
Convert text to numeric values, with strto* functions providing validation and range reporting.
atof(), atoi(), atol(), atoll(), strtod(), strtof(), strtol(), strtold(), strtoll(), strtoul(), strtoull()
Search and sort
Order arbitrary arrays and search sorted data through callback comparators.
Pseudo-random numbers
Generate and seed the standard deterministic pseudo-random sequence.
Multibyte and wide text
Convert locale-dependent multibyte characters and strings to or from wide characters.
Browse the Complete Function Index
The function catalog groups all 39 tutorials by job and includes live search. Start with the family that solves your current problem, then read the warning and failure contract before copying an example.
Frequently Asked Questions
Explore all 39 functions
Search by task and follow the complete tutorial sequence.
16 people found this page helpful
