Site Tools


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 memory
  • realloc(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 long
  • atoll(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 long
  • strtoul(str, &endptr, base): convert to unsigned long
  • strtoull(str, &endptr, base): convert to unsigned long long
  • strtof(str, &endptr), strtod(str, &endptr), strtold(str, &endptr): floating-point

Sorting and searching:

  • qsort(arr, count, size, cmp): quicksort in-place
  • bsearch(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 exit
  • getenv(name): get environment variable
  • system(cmd): execute shell command

Math:

  • abs(x): absolute value of int
  • labs(x): absolute value of long
  • llabs(x): absolute value of long long
  • div(a, b): quotient and remainder (returns div_t struct)
  • abs(x): absolute value
  • exit(code): terminate program
  • abort(): abnormal termination
h-stdlib.md · Last modified: by 127.0.0.1