cstdlib


Include file: <cstdlib>

The <cstdlib> header is a part of the C++ Standard Library that provides a collection of general-purpose functions, including those for dynamic memory management, random number generation, integer arithmetic, searching, sorting, and converting numbers to strings. This header is essentially the C++ version of the C standard library <stdlib.h>. It offers a wide range of utility functions that are commonly used in C++ programming for various tasks.

Key Characteristics

Example 1: Dynamic Memory Allocation

#include <cstdlib>
#include <iostream>
#include <cstring>

int main() {
    // Allocate memory for an integer
    int* ptr = (int*)malloc(sizeof(int));
    if (ptr == NULL) {
        std::cerr << "Memory allocation failed" << std::endl;
        return EXIT_FAILURE;
    }
    *ptr = 42;
    std::cout << "Allocated integer value: " << *ptr << std::endl;
    free(ptr);

    // Allocate memory for a string
    char* str = (char*)calloc(20, sizeof(char));
    if (str == NULL) {
        std::cerr << "Memory allocation failed" << std::endl;
        return EXIT_FAILURE;
    }
    strcpy(str, "Hello, World!");
    std::cout << "Allocated string: " << str << std::endl;

    // Reallocate memory
    str = (char*)realloc(str, 30 * sizeof(char));
    if (str == NULL) {
        std::cerr << "Memory reallocation failed" << std::endl;
        return EXIT_FAILURE;
    }
    strcat(str, " Extended!");
    std::cout << "Reallocated string: " << str << std::endl;

    free(str);
    return EXIT_SUCCESS;
}

Explanation:

Example 2: Random Number Generation

#include <cstdlib>
#include <ctime>
#include <iostream>

int main() {
    // Seed the random number generator
    std::srand(static_cast<unsigned int>(std::time(nullptr)));

    // Generate and print 5 random numbers
    for (int i = 0; i < 5; ++i) {
        int random_number = std::rand() % 100;  // Random number between 0 and 99
        std::cout << "Random number " << i + 1 << ": " << random_number << std::endl;
    }

    // Generate a random number in a specific range (e.g., 10 to 20)
    int min = 10, max = 20;
    int range_random = min + (std::rand() % (max - min + 1));
    std::cout << "Random number between " << min << " and " << max << ": " << range_random << std::endl;

    return EXIT_SUCCESS;
}

Explanation:

Example 3: String Conversion and Arithmetic Functions

#include <cstdlib>
#include <iostream>
#include <cmath>

int main() {
    // String to integer conversion
    const char* str_int = "123";
    int num_int = std::atoi(str_int);
    std::cout << "String to int: " << num_int << std::endl;

    // String to double conversion
    const char* str_double = "3.14159";
    double num_double = std::atof(str_double);
    std::cout << "String to double: " << num_double << std::endl;

    // Integer to string conversion
    char buffer[20];
    std::itoa(num_int, buffer, 10);  // Base 10
    std::cout << "Int to string: " << buffer << std::endl;

    // Absolute value
    int negative = -42;
    std::cout << "Absolute value of " << negative << ": " << std::abs(negative) << std::endl;

    // Division and modulus
    int dividend = 17, divisor = 5;
    std::div_t result = std::div(dividend, divisor);
    std::cout << dividend << " divided by " << divisor << " is " 
              << result.quot << " with remainder " << result.rem << std::endl;

    return EXIT_SUCCESS;
}

Explanation:

Example 4: Sorting and Searching

#include <cstdlib>
#include <iostream>
#include <algorithm>

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

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);

    // Sorting
    std::qsort(arr, n, sizeof(int), compare);

    std::cout << "Sorted array: ";
    for (int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    // Searching
    int key = 25;
    int* item = (int*)std::bsearch(&key, arr, n, sizeof(int), compare);

    if (item != NULL) {
        std::cout << key << " found at position " << (item - arr) << std::endl;
    } else {
        std::cout << key << " not found in the array" << std::endl;
    }

    return EXIT_SUCCESS;
}

Explanation:

Additional Considerations

  1. Memory Management: Always pair malloc(), calloc(), or realloc() with free() to avoid memory leaks.

  2. Random Number Quality: The rand() function provides basic pseudo-random numbers. For cryptographic purposes or high-quality randomness, use more sophisticated libraries.

  3. Portability: Some functions like itoa() are not part of the C++ standard and may not be available on all platforms.

  4. Error Handling: Many functions in <cstdlib> set the global variable errno on error. Check this or use return values to handle errors.

  5. C++ Alternatives: Modern C++ often provides safer alternatives, like <random> for random numbers and std::sort() for sorting.

Summary

The <cstdlib> header in C++ provides a wide array of utility functions:

While <cstdlib> offers powerful and flexible tools, modern C++ often provides safer and more type-safe alternatives. However, understanding and using <cstdlib> remains important for C++ programmers, especially when working with legacy code or when specific C-style functionalities are required. Always consider the C++ alternatives and use <cstdlib> functions judiciously, keeping in mind potential pitfalls like buffer overflows and memory leaks.

Related

Previous Page | Course Schedule | Course Content