<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
Include the header, allocate or convert carefully, then clean up or exit with a clear status.
Add #include <stdlib.h> at the top of the file.
Allocate with malloc/calloc, then check for NULL.
Parse numbers with strtol when input might be wrong; use atoi only for demos.
Call free for every successful allocation, or exit with EXIT_SUCCESS / EXIT_FAILURE.
Piece
Required?
Role
#include <stdlib.h>
Yes
Declares memory, exit, conversion, rand
Size in bytes
For malloc
Often n * sizeof(T)
NULL check
Yes after malloc
Allocation 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
Reference
Cheat Sheet
The calls you will reach for most often.
Topic
Detail
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 / srand
0…RAND_MAX; seed once
Try it
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.
Trace
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 ✓
Code
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;
}
Output
10 20 30
How It Works
Request bytes.n * sizeof(int) is portable across platforms.
Check NULL. Failed allocation returns NULL—exit with EXIT_FAILURE.
Use like an array. Index with p[i] after a successful malloc.
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).
Parse base 10.strtol reads leading digits into a long.
Get the end pointer.end points at the first unused character.
Detect empty parse. If end == text, no digits were found.
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;
}
Output (sample; sequence depends on your libc)
Five dice rolls: 4 4 3 5 5
How It Works
Seed once.srand(1) fixes the sequence on a given C library.
Call rand. Returns an int in 0 … RAND_MAX.
Map to 1–6.(rand() % 6) + 1 is a simple dice pattern (slight bias is fine for learning).
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);.
Analysis
Performance Notes
Approach
Cost
Best for
Stack arrays
Fast, automatic lifetime
Small fixed sizes
malloc / free
Heap overhead + fragmentation
Sizes known only at runtime
Many tiny mallocs
Expensive
Prefer one block or a pool
Allocate in larger chunks when you can. calloc zeroes memory (extra work) but avoids uninitialized reads.
Remember
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.