C stdlib.h Tutorial

Beginner
9 min read
Updated: Nov 2026
Starter example

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.

A useful mental model: stdlib.h functions often cross a boundary—automatic to dynamic storage, text to numbers, program to host, or bytes to wide characters. Boundary checks are the main lesson.

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.

FunctionUseBeginner check
malloc(size)Uninitialized bytesCheck NULL; initialize before reading.
calloc(count, size)Zero-filled bytes for an arrayCheck NULL; remember byte-zero nuance.
realloc(ptr, size)Resize an existing blockAssign to a temporary pointer first.
aligned_alloc(a, size)Explicitly aligned blockMake size a multiple of alignment.
free(ptr)End allocation lifetimeFree 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.

Questionatoi()strtol()
Were any digits consumed?Cannot tell reliablyCheck end != text
Where did parsing stop?Not availableInspect *end
Was long range exceeded?No dependable reportCheck errno == ERANGE
Can base prefixes be detected?Decimal onlyPass base 0
Rule of thumb: use 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.

C
#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

  1. Parse with evidence. strtol() reports where conversion stops, while errno reports range failure.
  2. Validate the intended domain. The program requires a positive value that can fit the later loop and indexing design.
  3. Allocate by element type. The byte count uses sizeof *values, and NULL is checked before writing.
  4. 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.

malloc(), calloc(), realloc(), free(), aligned_alloc()

Integer absolute value and division

Compute magnitudes or quotient-and-remainder pairs for standard integer widths.

abs(), labs(), llabs(), div(), ldiv(), lldiv()

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.

bsearch(), qsort()

Pseudo-random numbers

Generate and seed the standard deterministic pseudo-random sequence.

rand(), srand()

Environment

Read a named value from the host program environment.

getenv()

Multibyte and wide text

Convert locale-dependent multibyte characters and strings to or from wide characters.

mblen(), mbtowc(), wctomb(), mbstowcs(), wcstombs()

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.

  1. Memory first: learn malloc(), realloc(), and free() together.
  2. Validated conversion: compare atoi() with strtol().
  3. Generic arrays: use one safe comparator with qsort() and bsearch().
  4. Termination: understand handler and stream differences before choosing exit, quick exit, immediate exit, or abort.

Open all stdlib.h functions →

Frequently Asked Questions

It declares general utilities for allocation, conversion, termination, environment access, sorting, searching, pseudo-random values, integer helpers, and multibyte conversion.
Free every successful allocation exactly once when its lifetime ends. A NULL result owns no storage and may safely be passed to free().
strtol exposes whether digits were consumed, where conversion stopped, and whether the result exceeded the long range. atoi cannot reliably report those failures.
calloc initializes every byte to zero. That produces integer zero, but the C standard does not promise that all-bits-zero is every pointer or floating type's semantic zero.
Open the stdlib.h function index to search and browse all 39 tutorials by category.

Explore all 39 functions

Search by task and follow the complete tutorial sequence.

stdlib.h function index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

16 people found this page helpful