h-stdlib
Table of Contents
<stdlib.h>
<stdlib.h> covers memory allocation (malloc, calloc, free), type conversion (atoi, strtol), sorting/searching (qsort, bsearch), and process control (exit, abort). It's the “junk drawer” of the C standard library.
Always check malloc for NULL; always check qsort comparators carefully for overflow.
Example
This example sorts integers with qsort and binary-searches the result.
// compile: gcc -o stdlibexample stdlibexample.c // run: ./stdlibexample // description: sort array with qsort, then search it with bsearch #include <stdlib.h> #include <stdio.h> int cmp_int(const void* a, const void* b) { return *(int*)a - *(int*)b; } int main() { int arr[] = {5, 2, 8, 1, 9, 3}; int n = sizeof(arr) / sizeof(arr[0]); qsort(arr, n, sizeof(int), cmp_int); printf("sorted: "); 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"); return 0; }
Common functions
Memory allocation:
malloc(size): allocate memory (returns NULL on failure)calloc(count, size): allocate zeroed memoryrealloc(ptr, size): resize allocated memory (can move pointer)free(ptr): deallocate memory (safe to free NULL)
String to number conversion:
atoi(str): convert string to int (returns 0 on error, no error reporting)atol(str): convert string to longatoll(str): convert string to long long (C99)strtol(str, &endptr, base): convert to long (safer: reports errors, sets endptr)strtoll(str, &endptr, base): convert to long longstrtoul(str, &endptr, base): convert to unsigned longstrtoull(str, &endptr, base): convert to unsigned long longstrtof(str, &endptr),strtod(str, &endptr),strtold(str, &endptr): floating-point
Sorting and searching:
qsort(arr, count, size, cmp): quicksort in-placebsearch(key, arr, count, size, cmp): binary search (requires sorted array)
Pseudo-random numbers:
rand(): pseudo-random integer [0, RAND_MAX]srand(seed): seed generator (call once before first rand call)
Environment and exit:
exit(code): terminate program (flushes streams, calls atexit functions)abort(): terminate program (no cleanup, status ABORT)atexit(func): register function to call at exitgetenv(name): get environment variablesystem(cmd): execute shell command
Math:
abs(x): absolute value of intlabs(x): absolute value of longllabs(x): absolute value of long longdiv(a, b): quotient and remainder (returns div_t struct)abs(x): absolute valueexit(code): terminate programabort(): abnormal termination
h-stdlib.md · Last modified: by 127.0.0.1
