wiki: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; }
wiki/h-stdlib.md · Last modified: by 127.0.0.1
