C Mastery / stdlib.h: Conversion, Allocation, Environment
Part 3 — The Standard Library

stdlib.h: Conversion, Allocation, Environment

This chapter covers <stdlib.h>: numeric conversion functions, memory allocation (malloc/calloc/realloc/free), and environment/utility functions. Allocation is introduced here and treated in depth in Part 4.

Why This Matters

<stdlib.h> is one of the most-used headers. Conversion functions (atoi, strtol, strtod) are the bridge between strings and numbers; allocation functions are the bridge to the heap; environment functions connect the program to the OS.

Prerequisites

Core Concept

Conversion functions

int    atoi(const char *s);           /* ASCII to int (no error detection) */
long   strtol(const char *s, char **endp, int base);
double strtod(const char *s, char **endp);

strtol/strtod are the robust choices: they set *endp to the first unconverted character and report errors via errno and range checking.

Allocation functions

void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);
void *realloc(void *ptr, size_t size);
void  free(void *ptr);

Covered in depth in c.memory.2.

Environment and utilities

void exit(int status);
void abort(void);
int  system(const char *command);     /* platform-dependent */
char *getenv(const char *name);       /* not thread-safe in general */
int  rand(void);
void srand(unsigned seed);
void qsort(void *base, size_t nmemb, size_t size,
           int (*cmp)(const void *, const void *));
void *bsearch(const void *key, const void *base, size_t nmemb, size_t size,
              int (*cmp)(const void *, const void *));

Syntax

#include <stdlib.h>

long v = strtol(str, &end, 10);
int *p = malloc(sizeof *p);
qsort(arr, n, sizeof arr[0], compare);

Examples

Robust string-to-integer conversion

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>

int main(void)
{
    const char *s = "  123abc";
    char *end = NULL;
    errno = 0;
    long v = strtol(s, &end, 10);
    if (end == s) {
        printf("no digits\n");
    } else if (errno == ERANGE || v < INT_MIN || v > INT_MAX) {
        printf("out of range\n");
    } else {
        printf("value %ld, rest: %s\n", v, end);
    }
    return 0;
}

Expected output: value 123, rest: abc.

qsort with a comparator

#include <stdlib.h>

int cmp_int(const void *a, const void *b)
{
    const int *ia = a, *ib = b;
    return (*ia > *ib) - (*ia < *ib);
}

int main(void)
{
    int arr[] = {5, 2, 4, 1, 3};
    qsort(arr, 5, sizeof arr[0], cmp_int);
    return 0;
}

How It Works

Conversion functions parse the leading portion of a string, respecting optional whitespace and sign, and return the numeric value. Allocation functions obtain heap memory from the runtime. qsort sorts an array using the comparator; it is not stable and its performance is implementation-defined (usually introsort or quicksort).

Variations

atoi vs. strtol

atoi has no error detection (overflow is UB/undefined); strtol reports errors. Prefer strtol/strtod.

realloc semantics

realloc may move the block, invalidating the old pointer. If it fails, it returns NULL but leaves the original block intact. Never do p = realloc(p, n) directly — that leaks the original on failure.

Common Mistakes

Undefined Behavior

errno).

Portability

Under the Hood

strtol/strtod parse digit by digit, accumulating value while checking for overflow. Allocation functions call the C runtime allocator, which typically manages the heap with free lists and may call the OS for more memory (c.memory.5).

Practical Usage

Exercises

1. Write a robust integer parser using strtol that handles leading spaces, signs, and trailing garbage. 2. Demonstrate the p = realloc(p, n) leak and the correct pattern. 3. Use qsort and bsearch together on an array. 4. Explain why atoi("99999999999999999999") is not safe.

Deep Challenge

Implement a parse_int function that converts a decimal string to an int with full error reporting (overflow, no digits, trailing garbage), without using atoi and without invoking undefined behavior. Explain each check.

References

Verification

verified.`

Progress

Concept checkboxes

Mastery levels

ConceptCurrent level (0–8)Target level
c.lib.stdlib06