<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.
size_t, NULL, and EXIT_SUCCESS#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;
}
malloc() is used to allocate memory for a single integer.calloc() allocates memory for a string and initializes it to zero.realloc() is used to resize the allocated memory.free() is called to deallocate the memory and prevent memory leaks.EXIT_SUCCESS and EXIT_FAILURE macros for program termination status.#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;
}
srand() is used to seed the random number generator with the current time.rand() generates pseudo-random numbers.#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;
}
atoi() and atof() convert strings to integers and floating-point numbers, respectively.abs() computes the absolute value of an integer.div() performs integer division and returns both quotient and remainder.#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;
}
qsort() is used to sort the array using the quicksort algorithm.compare() for qsort() and bsearch().bsearch() performs a binary search on the sorted array.(item - arr) is used to find the index of the found item.Memory Management: Always pair malloc(), calloc(), or realloc() with free() to avoid memory leaks.
Random Number Quality: The rand() function provides basic pseudo-random numbers. For cryptographic purposes or high-quality randomness, use more sophisticated libraries.
Portability: Some functions like itoa() are not part of the C++ standard and may not be available on all platforms.
Error Handling: Many functions in <cstdlib> set the global variable errno on error. Check this or use return values to handle errors.
C++ Alternatives: Modern C++ often provides safer alternatives, like <random> for random numbers and std::sort() for sorting.
The <cstdlib> header in C++ provides a wide array of utility functions:
malloc(), calloc(), realloc(), and free().rand() and srand().atoi(), atof(), and itoa().abs() and div().qsort() and bsearch().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.