stdlib.h is the junk drawer of the C standard library. It covers dynamic memory allocation, process control, type conversions, random numbers, sorting, and searching — everything that did not fit cleanly into the other headers.
#include <stdlib.h> // dynamic memory void *p = malloc(1024); // allocate 1024 bytes, uninitialized void *z = calloc(16, sizeof(int)); // allocate and zero 16 ints p = realloc(p, 2048); // resize allocation free(p); // release memory // type conversion int i = atoi("42"); long l = atol("123456"); double d = atof("3.14"); long n = strtol("0xff", NULL, 16); // base 16, returns 255 // process exit(0); // flush buffers, terminate with status 0 abort(); // immediate abnormal termination (SIGABRT) int r = system("ls -l"); // run a shell command, return exit status char *home = getenv("HOME"); // read environment variable // random numbers srand(42); int x = rand(); // pseudo-random int in [0, RAND_MAX] // sort and search int cmp(const void *a, const void *b) { return *(int*)a - *(int*)b; } qsort(arr, n, sizeof(int), cmp); int *found = bsearch(&key, arr, n, sizeof(int), cmp);
malloc returns NULL on failure; always check. Passing NULL to free is safe and does nothing. realloc returns NULL on failure without freeing the original pointer, so assign to a temporary to avoid leaking the old allocation.
qsort is an unstable sort (order of equal elements is not preserved). bsearch requires the array to already be sorted. Both use a comparator returning negative/zero/positive, following the same convention as strcmp.
atexit(fn) registers a function to be called when exit is reached, in LIFO order. Useful for cleanup that should always run on normal termination — close log files, flush custom buffers, release external resources.
// compile: gcc -o sortdemo sortdemo.c // run: ./sortdemo // description: sort an integer array with qsort, then binary-search it #include <stdlib.h> #include <stdio.h> int cmp_int(const void *a, const void *b) { return *(int*)a - *(int*)b; } int main(void) { int arr[] = {5, 2, 8, 1, 9, 3}; int n = sizeof(arr) / sizeof(arr[0]); qsort(arr, n, sizeof(int), cmp_int); for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); int key = 8; int *found = bsearch(&key, arr, n, sizeof(int), cmp_int); printf("search for 8: %s\n", found ? "found" : "not found"); key = 7; found = bsearch(&key, arr, n, sizeof(int), cmp_int); printf("search for 7: %s\n", found ? "found" : "not found"); return 0; }
The comparator subtracts the two values, which works for integers that are far from INT_MIN/INT_MAX. For general safety, use (*(int*)a > *(int*)b) - (*(int*)a < *(int*)b) to avoid overflow on extreme values.