C stdlib.h Header

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is stdlib.h?

<stdlib.h> is the C general utilities header: dynamic memory (malloc / free), process exit, string-to-number conversion, and simple random numbers.

Remember
#include <stdlib.h>

malloc / calloc / realloc / free  → heap memory
exit(EXIT_SUCCESS | EXIT_FAILURE) → end the program
atoi / strtol / strtod            → string → number
rand / srand                      → pseudo-random ints

check malloc for NULL
free once — then do not use the pointer
prefer strtol over atoi for real input
UsePrefer
Growable arrays / buffersmalloc + free
Parse user / file numbersstrtol (not bare atoi)
Console / file text I/Ostdio.h

How to Use stdlib.h in C

Include the header, allocate or convert carefully, then clean up or exit with a clear status.

  1. Add #include <stdlib.h> at the top of the file.
  2. Allocate with malloc/calloc, then check for NULL.
  3. Parse numbers with strtol when input might be wrong; use atoi only for demos.
  4. Call free for every successful allocation, or exit with EXIT_SUCCESS / EXIT_FAILURE.
PieceRequired?Role
#include <stdlib.h>YesDeclares memory, exit, conversion, rand
Size in bytesFor mallocOften n * sizeof(T)
NULL checkYes after mallocAllocation can fail

Pseudocode

Pseudocode
include stdlib.h

p = malloc(n * sizeof(type))
if p is NULL:
    exit(EXIT_FAILURE)
use p ...
free(p)
p = NULL   // optional safety

value = strtol(text, &end, 10)
if end == text or *end not end-of-string:
    handle bad input

srand(seed once)
r = rand() % N

Cheat Sheet

The calls you will reach for most often.

TopicDetail
Header#include <stdlib.h>
malloc(n)Allocate n bytes (uninitialized)
calloc(c, s)Allocate c*s bytes, zero-filled
free(p)Release a heap block
exit(code)EXIT_SUCCESS (0) or EXIT_FAILURE
strtol(s, &end, 10)Parse long; check end for errors
atoi(s)Quick int parse — no error reporting
rand / srand0…RAND_MAX; seed once

Live Preview

Simulate common stdlib.h patterns: allocation, parsing, and a simple random roll.

Browser simulation of stdlib ideas (same concepts as the C examples below).

Result
p = malloc(5 * sizeof(int));
if (p == NULL) → fail
p[0] = 10; ...
free(p);

Rule: every successful malloc needs one free.

Worked Walkthrough — Allocate Three Ints

Request heap space for three ints, fill them, print, then free.

Calculation
bytes = 3 * sizeof(int)   // e.g. 3 * 4 = 12

p = malloc(12)
  NULL? → out of memory → EXIT_FAILURE

p[0] = 10
p[1] = 20
p[2] = 30

print → 10 20 30

free(p)
  heap block returned
  do not read p afterward ✓

C Examples

Compile with gcc file.c -std=c11 -o out. Link nothing extra for these utilities.

Example 1 — malloc and free

Allocate an array on the heap, fill it, print it, then release the memory.

C
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int n = 3;
    int *p = malloc((size_t)n * sizeof(int));
    int i;

    if (p == NULL) {
        fprintf(stderr, "malloc failed\n");
        return EXIT_FAILURE;
    }

    for (i = 0; i < n; i++) {
        p[i] = (i + 1) * 10;
    }
    for (i = 0; i < n; i++) {
        printf("%d ", p[i]);
    }
    printf("\n");

    free(p);
    return EXIT_SUCCESS;
}

How It Works

  1. Request bytes. n * sizeof(int) is portable across platforms.
  2. Check NULL. Failed allocation returns NULL—exit with EXIT_FAILURE.
  3. Use like an array. Index with p[i] after a successful malloc.
  4. Free once. free(p) returns the block; do not free it again.

Example 2 — Parse with strtol

Convert a string to a long and detect invalid input using an end pointer (safer than atoi).

C
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const char *text = "42abc";
    char *end;
    long value = strtol(text, &end, 10);

    if (end == text) {
        printf("No digits found\n");
        return EXIT_FAILURE;
    }

    printf("value = %ld\n", value);
    printf("stopped at: '%s'\n", end);

    return EXIT_SUCCESS;
}

How It Works

  1. Parse base 10. strtol reads leading digits into a long.
  2. Get the end pointer. end points at the first unused character.
  3. Detect empty parse. If end == text, no digits were found.
  4. See leftovers. Here "abc" remains—useful for validation. Pair with errno for overflow.

Example 3 — Seeded rand Dice Roll

Seed once, then roll a value from 1 to 6. The same seed repeats the same sequence (good for demos).

C
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int i;

    srand(1);  /* fixed seed → repeatable demo */

    printf("Five dice rolls: ");
    for (i = 0; i < 5; i++) {
        printf("%d ", (rand() % 6) + 1);
    }
    printf("\n");

    return EXIT_SUCCESS;
}

How It Works

  1. Seed once. srand(1) fixes the sequence on a given C library.
  2. Call rand. Returns an int in 0 … RAND_MAX.
  3. Map to 1–6. (rand() % 6) + 1 is a simple dice pattern (slight bias is fine for learning).
  4. Vary in real apps. Often people pass time(NULL) from time.h as the seed.

Edge Cases & Pitfalls

Check these before using heap memory or conversions in real code.

null

Always check malloc for NULL

Out-of-memory returns NULL. Writing through it is undefined behavior.

free

No double-free or use-after-free

Free each block once. After free, do not read or write through that pointer.

atoi

atoi hides errors

atoi("oops") and atoi("0") both yield 0. Prefer strtol with an end pointer.

realloc

Save the old pointer on realloc

If realloc fails it returns NULL but the old block remains. Use a temporary: tmp = realloc(p, n);.

Performance Notes

ApproachCostBest for
Stack arraysFast, automatic lifetimeSmall fixed sizes
malloc / freeHeap overhead + fragmentationSizes known only at runtime
Many tiny mallocsExpensivePrefer one block or a pool

Allocate in larger chunks when you can. calloc zeroes memory (extra work) but avoids uninitialized reads.

Key Takeaways

  • Role: heap memory, exit status, conversions, and simple randomness.
  • Memory: check NULL, free once, never use after free.
  • Parse: prefer strtol over atoi for real input.
  • Exit: EXIT_SUCCESS / EXIT_FAILURE communicate status clearly.

One line: stdlib.h covers heap, exit, and conversions—allocate carefully and free what you own.

Frequently Asked Questions

stdlib.h is the general utilities header. It provides dynamic memory (malloc, calloc, realloc, free), process control (exit, abort), string-to-number conversion (atoi, strtol, strtod), random numbers (rand, srand), and macros like EXIT_SUCCESS and RAND_MAX.
malloc(size) allocates size bytes with uninitialized contents. calloc(count, size) allocates count * size bytes and zeroes them. Prefer calloc when you want a clean zero-filled block.
realloc(ptr, new_size) grows or shrinks a block from malloc/calloc/realloc. On failure it returns NULL and leaves the old block valid—assign to a temporary pointer so you do not lose the original.
atoi reports no errors: bad input looks like 0. Prefer strtol with an end pointer to detect parse failures. Use atoi only for quick demos with trusted strings.
free(ptr) returns heap memory from malloc/calloc/realloc. Call free once per allocation. Do not use the pointer afterward unless you set it to NULL. Double-free and use-after-free are serious bugs.
rand() returns 0…RAND_MAX. srand(seed) sets the sequence; the same seed repeats the same values. Call srand once at startup (often with time(NULL)). rand is not cryptographically secure.

Next: string.h

Work with C strings: length, copy, compare, and memory blocks.

string.h tutorial →

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.

9 people found this page helpful