C stdlib.h Library: Essential Functions for Memory Management and More

The <stdlib.h> library in C offers a range of functions that are vital for memory management, random number generation, string conversion to numbers, and various other utilities. Understanding these functions is essential for effective C programming.



C stdlib.h Library

The <stdlib.h> header provides a set of functions that are useful for memory management, random number generation, converting strings to numbers, and more.

Common C stdlib Functions

Here are some of the common functions provided by the stdlib.h library:

Function Description
abs() Returns the absolute (positive) value of an integer.
atof() Converts a string to a double.
atoi() Converts a string to an integer.
atol() Converts a string to a long integer.
atoll() Converts a string to a long long integer.
calloc() Allocates dynamic memory and initializes it to zero.
div() Performs integer division and returns the quotient and remainder.
exit() Terminates the program.
free() Deallocates dynamic memory.
malloc() Allocates dynamic memory.
qsort() Sorts the elements of an array.
rand() Generates a random integer.
realloc() Reallocates dynamic memory.
srand() Seeds the random number generator.

Example: Memory Allocation and Random Numbers

Let’s see an example of how to use some stdlib.h functions to allocate memory dynamically, generate random numbers, and deallocate memory:

Example: Dynamic Memory Allocation and Random Numbers

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

int main() {
    // Seed the random number generator
    srand(time(0));

    // Allocate memory for an array of 5 integers
    int *arr = (int *)malloc(5 * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    // Fill the array with random numbers and print them
    for (int i = 0; i < 5; i++) {
        arr[i] = rand() % 100;  // Random number between 0 and 99
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    // Deallocate memory
    free(arr);

    return 0;
}

Output:

Output

arr[0] = 23
arr[1] = 76
arr[2] = 45
arr[3] = 12
arr[4] = 89

This program allocates memory dynamically for 5 integers, fills the array with random numbers, and then deallocates the memory. Note the use of rand() to generate random numbers and free() to release the allocated memory.