stdlib.h: Memory, Exit & Sorting in C
stdlib.h is the general-utility drawer: dynamic memory (malloc family), program control (exit, atexit, abort), integers (abs, atoi — prefer strtol), randomness (rand/srand), searching/sorting (bsearch/qsort), and environment (getenv, system). It has no single theme beyond everyday machinery every program eventually needs.
Two habits matter most: check allocation results (malloc can return NULL — dereferencing it segfaults), and exit with meaningful codes (EXIT_SUCCESS/EXIT_FAILURE) so shells and CI can react. The rest is vocabulary to recognize on sight.
Memory entry points
malloc/calloc/realloc/free live here — the only sanctioned heap interface, detailed in the memory module.
Exit deliberately
exit(EXIT_FAILURE) ends with a code; atexit() registers cleanup handlers that run before termination.
Quick conversions and math
abs/atoi for the trivial cases (validated strtol for real ones), rand/srand for casual randomness.
Environment access
getenv("HOME") reads environment variables (NULL when absent); system() shells out — convenient, injection-prone, sandbox carefully.
#include <stdio.h>#include <stdlib.h> int main(void) { int *a = malloc(3 * sizeof *a); if (!a) { fprintf(stderr, "no memory\n"); return EXIT_FAILURE; } a[0] = 1; printf("%d\n", a[0]); free(a); return EXIT_SUCCESS;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.