Chapter 27Intermediate
C stdlib.h Library Reference
Complete reference for stdlib.h - memory allocation, string conversion, random numbers, sorting, and program control.
20 min readUpdated 2024-12-16
stdlib.hmallocfreeatoirandqsortexit
What You Will Learn
- ✓Use memory functions (malloc, free)
- ✓Convert strings to numbers
- ✓Generate random numbers
- ✓Sort and search arrays
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
void *malloc(size_t size);
size: Number of bytes to allocate
Returns: Pointer to allocated memory, or NULL
main.c
C
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
void *calloc(size_t num, size_t size);
num: Number of elements
size: Size of each element
main.c
C
int *arr = (int *)calloc(5, sizeof(int));// Memory is ZERO-INITIALIZED (all elements = 0)printf("%d\n", arr[0]); // Output: 0realloc() - Resize Memory
void *realloc(void *ptr, size_t new_size);
ptr: Pointer to existing memory
new_size: New size in bytes
main.c
C
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
void free(void *ptr);
main.c
C
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) |
conversions.c
C
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()
int rand(void);
Returns pseudo-random number (0 to RAND_MAX)
srand()
void srand(unsigned int seed);
Seeds the random number generator
random.c
C
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
void qsort(void *base, size_t num, size_t size, int (*compare)(const void*, const void*));
base: Pointer to array
num: Number of elements
size: Size of each element
compare: Comparison function
main.c
C
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
void *bsearch(const void *key, const void *base, size_t num, size_t size, int (*compare)(...));
main.c
C
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 |
program_control.c
C
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 |
main.c
C
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 208Summary
🎯 Key Functions
Memory:
malloc, calloc, realloc, free
Conversion:
atoi, atof, strtol, strtod
Random:
rand, srand
Program:
exit, abort, system, getenv
09Next Steps
Learn about string manipulation functions: