C - Purpose of stdlib.h

In C, stdlib.h stands for Standard Library Header.
It provides functions for general-purpose utilities — such as memory allocation, process control, conversions, random numbers, and searching/sorting.


1. Purpose of stdlib.h

When you include:

#include <stdlib.h>

you get:

  • Function prototypes for commonly used utility functions.

  • Macros for constants like EXIT_SUCCESS and EXIT_FAILURE.

  • Type definitions like size_t, div_t, ldiv_t.

Without including it, you may get compiler warnings or errors when calling these functions.


2. Major Features Provided by stdlib.h

a) Memory Management

  • malloc(size_t size) – Allocates memory

  • calloc(size_t n, size_t size) – Allocates and initializes memory to zero

  • realloc(void *ptr, size_t size) – Changes size of previously allocated memory

  • free(void *ptr) – Frees allocated memory


b) Process Control

  • exit(int status) – Ends the program with a status code

  • abort() – Immediately terminates the program abnormally

  • system(const char *command) – Runs a system command


c) Conversions

  • String to numbers

    • atoi(const char *str) – String to int

    • atof(const char *str) – String to double

    • atol(const char *str) – String to long

    • strtol(), strtoul(), strtod() – Safer, more flexible conversions

  • Number to string

    • Usually handled via sprintf() from stdio.h, but combined with stdlib.h conversions for data processing.


d) Random Numbers

  • rand() – Generates pseudo-random numbers (0 to RAND_MAX)

  • srand(unsigned int seed) – Seeds the random number generator


e) Searching and Sorting

  • qsort() – General-purpose quicksort function

  • bsearch() – Binary search function for sorted arrays


f) Arithmetic Functions

  • abs(int n) – Absolute value of integer

  • labs(long n) – Absolute value of long integer

  • div(), ldiv() – Integer division returning quotient and remainder in a struct


g) Important Macros

  • EXIT_SUCCESS – Successful program termination (usually 0)

  • EXIT_FAILURE – Unsuccessful program termination (non-zero)

  • RAND_MAX – Maximum value returned by rand()


3. Example

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

int main() {
    // Random number example
    srand(42);
    printf("Random: %d\n", rand());

    // Memory allocation example
    int *arr = (int *)malloc(5 * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        exit(EXIT_FAILURE);
    }
    
    for (int i = 0; i < 5; i++) arr[i] = i + 1;
    
    for (int i = 0; i < 5; i++) printf("%d ", arr[i]);
    printf("\n");
    
    free(arr);
    return EXIT_SUCCESS;
}