C stdlib.h Library Reference
Complete reference for stdlib.h - memory allocation, string conversion, random numbers, sorting, and program control.
Track Your Progress
Sign in to save your learning progress
What You Will Learn
- ✓Use memory functions (malloc, free)
- ✓Convert strings to numbers
- ✓Generate random numbers
- ✓Sort and search arrays
?Why is stdlib.h Essential?
stdlib.h is the Swiss Army knife of C programming. Almost every non-trivial program needs it for memory, conversions, or program control.
Memory
malloc, free
Convert
atoi, strtol
Random
rand, srand
Sort
qsort, bsearch
01Introduction to stdlib.h
What is stdlib.h?
<stdlib.h> (Standard Library) provides essential utilities: memory allocation, type conversions, random numbers, sorting, and program control.
Key Functions Overview
| Category | Functions |
|---|---|
| Memory | malloc, calloc, realloc, free |
| Conversion | atoi, atof, atol, strtol, strtod |
| Random | rand, srand |
| Sort/Search | qsort, bsearch |
| Program | exit, abort, atexit, system |
| Math | abs, labs, div, ldiv |
02Memory Allocation Functions
malloc() - Allocate Memory
int *arr = (int *)malloc(5 * sizeof(int));if (arr == NULL) { printf("Allocation failed!\n"); return 1;}// Memory is UNINITIALIZED (garbage values)calloc() - Allocate and Zero-Initialize
int *arr = (int *)calloc(5, sizeof(int));// Memory is ZERO-INITIALIZED (all elements = 0)printf("%d\n", arr[0]); // Output: 0realloc() - Resize Memory
int *arr = malloc(5 * sizeof(int));// Need more space? Resize!int *temp = realloc(arr, 10 * sizeof(int));if (temp != NULL) { arr = temp; // Safe pattern}free() - Deallocate Memory
int *arr = malloc(5 * sizeof(int));// Use the memory...free(arr); // Release memoryarr = NULL; // Prevent dangling pointer03String Conversion Functions
| Function | Prototype | Description |
|---|---|---|
| atoi() | int atoi(const char *str) | String → int |
| atof() | double atof(const char *str) | String → double |
| atol() | long atol(const char *str) | String → long |
| strtol() | long strtol(const char *str, char **end, int base) | String → long (with base) |
| strtod() | double strtod(const char *str, char **end) | String → double (safer) |
1#include <stdlib.h>2#include <stdio.h>34int main() {5 // Basic conversions6 int num = atoi("42"); // 427 double pi = atof("3.14159"); // 3.141598 long big = atol("1000000"); // 10000009 10 // strtol with base (hex, binary, etc.)11 char *end;12 long hex = strtol("FF", &end, 16); // 255 (hex)13 long bin = strtol("1010", &end, 2); // 10 (binary)14 long dec = strtol("123abc", &end, 10); // 123, end points to "abc"15 16 printf("Hex FF = %ld\n", hex);17 printf("Binary 1010 = %ld\n", bin);18 19 return 0;20}strtol() vs atoi()
Use strtol() for better error handling — it tells you where parsing stopped and supports different bases (2, 8, 10, 16).
04Random Number Functions
rand()
Returns pseudo-random number (0 to RAND_MAX)
srand()
Seeds the random number generator
1#include <stdlib.h>2#include <stdio.h>3#include <time.h>45int main() {6 // Seed with current time (do once at program start!)7 srand(time(NULL));8 9 // Random number 0 to RAND_MAX10 int r1 = rand();11 12 // Random 0-9913 int r2 = rand() % 100;14 15 // Random 1-6 (dice roll)16 int dice = (rand() % 6) + 1;17 18 // Random 10-5019 int r3 = (rand() % 41) + 10;20 21 printf("Dice: %d\n", dice);22 printf("Range 10-50: %d\n", r3);23 24 return 0;25}Important
Call srand() only once at program start. Calling it repeatedly with same seed produces same sequence!
05Sorting and Searching
qsort() - Quick Sort
int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); // Ascending}int main() { int arr[] = {5, 2, 8, 1, 9}; int n = sizeof(arr) / sizeof(arr[0]); qsort(arr, n, sizeof(int), compare); // arr is now: {1, 2, 5, 8, 9} return 0;}bsearch() - Binary Search
int arr[] = {1, 2, 5, 8, 9}; // Must be sorted!int key = 5;int *result = bsearch(&key, arr, 5, sizeof(int), compare);if (result != NULL) { printf("Found: %d\n", *result);} else { printf("Not found\n");}06Program Control Functions
| Function | Prototype | Description |
|---|---|---|
| exit() | void exit(int status) | Terminate program normally |
| abort() | void abort(void) | Terminate abnormally |
| atexit() | int atexit(void (*func)(void)) | Register exit handler |
| system() | int system(const char *cmd) | Execute shell command |
| getenv() | char *getenv(const char *name) | Get environment variable |
1#include <stdlib.h>2#include <stdio.h>34void cleanup() {5 printf("Cleanup called!\n");6}78int main() {9 // Register cleanup function10 atexit(cleanup);11 12 // Get environment variable13 char *path = getenv("PATH");14 printf("PATH: %.50s...\n", path);15 16 // Execute system command17 system("echo Hello from shell!");18 19 // Normal exit (calls atexit handlers)20 exit(EXIT_SUCCESS); // or exit(0)21 22 // Never reached23 return 0;24}07Integer Math Functions
| Function | Prototype | Description |
|---|---|---|
| abs() | int abs(int n) | Absolute value of int |
| labs() | long labs(long n) | Absolute value of long |
| div() | div_t div(int num, int den) | Quotient and remainder |
| ldiv() | ldiv_t ldiv(long num, long den) | Long quotient and remainder |
int x = abs(-42); // 42long y = labs(-100000L); // 100000div_t result = div(17, 5);printf("17 / 5 = %d remainder %d\n", result.quot, result.rem);// Output: 17 / 5 = 3 remainder 2!Code Pitfalls: Common Mistakes & What to Watch For
Code copied from the internet often has stdlib.h code that works in simple cases but fails in production. Here are critical mistakes beginners make:
Watch out: Missing malloc() return value check
Code often looks like:
// Immediately uses ptr without NULL check!
malloc() can return NULL if memory allocation fails. Always check!
Watch out: Using atoi() without error handling
atoi("abc") returns 0, which is indistinguishable from atoi("0"). This is often ignored and doesn't validate input. Use strtol() for robust parsing!
Watch out: Not seeding rand() properly
Without srand(time(NULL)), rand() produces the same sequence every run. Copied code often forgets this, leading to predictable "random" values.
This causes memory leaks with realloc()
Copied code often:
// If realloc fails, original pointer is lost = memory leak!
Frequently Asked Questions
Q: How do I generate random numbers in a specific range?
Use modulo with offset: rand() % (max - min + 1) + min. For example, to get numbers between 10 and 20: rand() % 11 + 10. Note: this has slight bias for large ranges; for cryptographic use, use a proper library.
Q: What's the difference between malloc() and calloc()?
malloc() allocates memory without initializing it (contains garbage). calloc() allocates AND initializes all bytes to zero. Use calloc() when you need guaranteed zero-initialization, like for arrays or structs.
Q: Why does rand() give the same numbers every time?
rand() uses a pseudo-random algorithm that needs a "seed" value. Without seeding, it uses 1 by default. Call srand(time(NULL)) once at program start to get different sequences each run.
Q: When should I use exit() vs return?
Use return in main() for normal termination. Use exit()when terminating from any function, especially to trigger atexit() handlers. Use abort()only for abnormal/emergency termination (skips cleanup).
Q: What's the difference between exit() and _Exit()?
exit() performs cleanup: it calls atexit() handlers, flushes stdio buffers, and closes files properly. _Exit() (C99) terminates immediately without any cleanup. Use _Exit() only when you need to avoid running cleanup code, such as in a child process after fork().
Q: How do I safely reallocate memory?
Never assign realloc() directly to your original pointer. If realloc() fails, it returns NULL but doesn't free the original memory. Use a temporary: void *tmp = realloc(ptr, newSize); if (tmp) ptr = tmp;This prevents memory leaks when reallocation fails.
Q: Why does qsort need a comparison function?
qsort() is generic—it doesn't know what you're sorting. Your comparison function tells it how to compare two elements. Return negative if first is less, positive if greater, zero if equal. This design allows sorting any data type with the same function.
Q: Is system() safe to use?
system() is convenient but risky. Never pass user input directly to system() — it's a major security vulnerability (command injection). For production code, use specific system calls like fork()/exec() on Unix or CreateProcess() on Windows.
Q: Why use strtol() instead of atoi()?
atoi() can't detect errors — it returns 0 for both "0" and invalid input like "abc". strtol() provides error detection via the endptr parameter and errno, making it essential for validating user input.
Q: What's the difference between exit() and abort()?
exit() performs cleanup: flushes buffers, closes files, calls atexit() handlers.abort() terminates immediately without cleanup, typically generating a core dump for debugging. Use exit() for normal termination, abort() for fatal errors.
Q: How do I generate random numbers in a specific range?
Use modulo: rand() % (max - min + 1) + min for range [min, max]. For better distribution, especially with large ranges, use:(int)((double)rand() / RAND_MAX * (max - min + 1)) + min.
10Summary
Key Functions
Memory:
malloc, calloc, realloc, free
Conversion:
atoi, atof, strtol, strtod
Random:
rand, srand
Program:
exit, abort, system, getenv
11Memory Management Best Practices
Always Free What You Allocate
For every malloc(), there should be a corresponding free(). Track ownership of allocated memory clearly in your code design.
Use calloc for Zero-Initialized Memory
When you need zero-initialized memory, use calloc() instead ofmalloc() followed by memset(). It's cleaner and often optimized by the OS to provide zero pages efficiently.
Test Your Knowledge
Related Tutorials
C stdio.h Library Reference
Complete reference for stdio.h - all printf, scanf, and file functions with prototypes, parameters, and examples.
C string.h Library Reference
Complete reference for string.h - strlen, strcpy, strcat, strcmp, searching, and memory functions.
Dynamic Memory Allocation
Allocate memory at runtime! Use malloc, calloc, realloc, and free. Create arrays whose size you don't know until the program runs.
Have Feedback?
Found something missing or have ideas to improve this tutorial? Let us know on GitHub!