← GCC/C Index

⚙️ <stdlib.h> — General Utilities — Memory, Conversion, Process

The Swiss-army knife of C. Covers dynamic memory allocation, process control, number conversion, sorting, and pseudo-random numbers.

Include: #include <stdlib.h> | Compile: gcc -Wall -o prog prog.c

📋 Functions & Macros

NamePrototype / ValueDescription
mallocvoid *malloc(size_t size)Allocate size bytes; returns NULL on failure
callocvoid *calloc(size_t n, size_t size)Allocate n×size zeroed bytes
reallocvoid *realloc(void *ptr, size_t size)Resize a previously allocated block
freevoid free(void *ptr)Release allocated memory
atoiint atoi(const char *s)Convert string to int (no error check)
atollong atol(const char *s)Convert string to long
atofdouble atof(const char *s)Convert string to double
strtollong strtol(const char *s, char **end, int base)String to long with base & error info
strtoulunsigned long strtoul(const char *s, char **end, int base)String to unsigned long
strtoddouble strtod(const char *s, char **end)String to double with error info
randint rand(void)Return pseudo-random int in [0, RAND_MAX]
srandvoid srand(unsigned int seed)Seed the pseudo-random number generator
absint abs(int x)Absolute value of int
labslong labs(long x)Absolute value of long
qsortvoid qsort(void *base, size_t n, size_t sz, int (*cmp)(const void*, const void*))Sort array
bsearchvoid *bsearch(const void *key, const void *base, size_t n, size_t sz, int (*cmp)(const void*, const void*))Binary search
exitvoid exit(int status)Terminate program with status code
abortvoid abort(void)Raise SIGABRT — abnormal termination
atexitint atexit(void (*fn)(void))Register function to call on normal exit
getenvchar *getenv(const char *name)Return value of environment variable
systemint system(const char *cmd)Execute shell command (use with caution)

💡 Example Program

Copy, save as demo.c, and compile with the command shown at the bottom.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int cmp_int(const void *a, const void *b) {
    return (*(int *)a - *(int *)b);
}

int main(void) {
    int *arr = malloc(5 * sizeof(int));
    if (!arr) { perror("malloc"); return 1; }

    srand((unsigned)time(NULL));
    for (int i = 0; i < 5; i++) arr[i] = rand() % 100;

    printf("Before sort: ");
    for (int i = 0; i < 5; i++) printf("%d ", arr[i]);
    printf("\n");

    qsort(arr, 5, sizeof(int), cmp_int);

    printf("After sort:  ");
    for (int i = 0; i < 5; i++) printf("%d ", arr[i]);
    printf("\n");

    free(arr);

    char *end;
    long val = strtol("0xFF", &end, 16);
    printf("0xFF = %ld\n", val);
    return 0;
}
/* Compile: gcc -Wall -o stdlib_demo stdlib_demo.c */

← <string.h>  |  🏠 Index  |  <ctype.h> →