Name already in use
cpp-docs / docs / standard-library / cstdlib.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Includes the C Standard library header <stdlib.h> and adds the associated names to the std namespace. Including this header ensures that the names declared using external linkage in the C standard library header are declared in the std namespace.
[!NOTE] <stdlib.h> doesn’t include the type wchar_t .
Namespace and Macros
Exposition only functions
Start and termination functions
|_Exit||Terminates program without using destructors or registered functions.|
|abort||Terminates program without using destructors.|
|atexit||Registers function for program termination.|
|exit||Destroys objects with thread and static storage, then returns control.|
|at_quick_exit||Registers function without arguments for program termination.|
|quick_exit||Registers function with preserved objects for program termination.|
|getenv||See C standard library reference.|
|system||See C standard library reference.|
The program is terminated without executing destructors for objects of automatic, thread, or static storage duration and without calling functions passed to atexit() . The function _Exit is signal-safe.
The program is terminated without executing destructors for objects of automatic, thread, or static storage duration and without calling functions passed to atexit() . The function abort is signal-safe.
Zero if the registration succeeds, non-zero if it fails.
The at_quick_exit() functions register a function func , which is called without arguments when quick_exit() is called. A call to at_quick_exit() that doesn’t happen before all calls to quick_exit() may not succeed. The at_quick_exit() functions don’t introduce a data race. The order of registration may be indeterminate if at_quick_exit() was called from more than one thread. Since at_quick_exit() registrations are distinct from the atexit() registrations, applications may need to call both registration functions using the same argument. MSVC supports the registration of at least 32 functions.
The atexit() functions register the function pointed to by func to be called without arguments at normal program termination. A call to atexit() that doesn’t happen before a call to exit() may not succeed. The atexit() functions don’t introduce a data race.
Returns zero if the registration succeeds, nonzero if it fails.
First, objects with thread storage duration and associated with the current thread are destroyed.
Next, objects with static storage duration are destroyed and functions registered by calling atexit() are called. Automatic objects aren’t destroyed when exit() is called. If control leaves a registered function called by exit() because the function doesn’t provide a handler for a thrown exception, std::terminate() is called. A function is called once for every time it’s registered. Objects with automatic storage duration are all destroyed in a program whose main function contains no automatic objects and executes the call to exit() . Control can be transferred directly to such a main function by throwing an exception that’s caught in main .
Next, all open C streams (as mediated by the function signatures declared in <cstdio> ) with unwritten buffered data are flushed, all open C streams are closed, and all files created by calling tmpfile() are removed.
Finally, control is returned to the host environment. When status is zero or EXIT_SUCCESS , an implementation-defined form of the status successful termination is returned. MSVC returns a value of zero. If status is EXIT_FAILURE , MSVC returns a value of 3. Otherwise, MSVC returns the status parameter value.
Generally, functions registered by calls to at_quick_exit() are called in the reverse order of their registration. This order doesn’t apply to functions registered after other registered functions have already been called. No objects are destroyed when quick_exit() is called. If control leaves a registered function called by quick_exit() because the function doesn’t provide a handler for a thrown exception, std::terminate() is called. A function registered via at_quick_exit() is invoked by the thread that calls quick_exit() , which can be a different thread than the one that registered it. That means registered functions shouldn’t rely on the identity of objects that have thread storage duration. After calling registered functions, quick_exit() calls _Exit(status) . The standard file buffers aren’t flushed. The function quick_exit() is signal-safe when the functions registered with at_quick_exit() are.
Memory allocation functions
These functions have the semantics specified in the C standard library. MSVC doesn’t support the aligned_alloc function. C11 specified aligned_alloc() in a way that’s incompatible with the Microsoft implementation of free() , namely, that free() must be able to handle highly aligned allocations.
cstdlib in C++ – Explained
Author: Dori Exterman Published On: September 14, 2021 Estimated reading time: 6 minutes
What Is cstdlib in C++?
The C++ Standard Library header file (cstdlib in C++) is the header for one of the most widely used libraries by programmers of the language. This header defines a collection of functions and macros to facilitate efficient, high-performing, standardized C++ code across teams and platforms.
C++ is a popular programming language and one of the initial reasons for its rise in popularity was compatibility with C, which was a popular and well-established language at the time, and in fact, still is. This compatibility not only meant that it was easier for programmers to adapt but, perhaps more importantly, C++ developers were able to take advantage of pre-existing C code.
Rather than recreate everything from the core functions onward, programmers were able to re-use mature code blocks during a reasonably-paced transition to C++. Specifically, they were able to use the C Standard library header, stdlib.h. Fast-forward to today, cstdlib in C++ is the enhanced C++ version of the original <stdlib.h>.
cstdlib in C++ vs stdlib.h
The C Standard Library Header, <stdlib.h>, offers C programmers reliable and efficient functions for dynamic memory allocation, conversion between datatypes, pseudo-random number generation, process control, searching and sorting, math, and multibyte or wide characters. In addition to these common routines, oft-used constants exist to promote code standardization across organizations and platforms.
Headers and Namespaces
In the original C++ specification, C++98, it stated that to correctly use functions that were inherited from the C library was by using a <c –name–> header. For example, in a traditional C program, one might include “string.h”, whereas, in C++, an identical project would include <cstring>. Furthermore, with the advent of namespaces, newly-written C++ library functions were no longer to be defined in the global, unqualified namespace. Rather, they would be declared only in the standard namespace, std.
Moving forward, using cstdlib for C++ implies a guarantee that everything included in <stdlib.h> is declared in the std namespace. As such, when developers want to use functions in the Standard Library, they have to be qualified. This can be done explicitly, or with the using directive, as in the following example:
Figure 1 : Example of using std::shared_ptr as part of a double-linked list
In the left column, the unqualified use of shared_ptr<> reports an error because the declaration is not in the global namespace. In the middle column, the namespace is explicitly declared, pointing to where the compiler can find it. In the rightmost column, the using namespace std directive directs the compiler to std to search for functions that do not exist inside the local or global scopes. It is to be noted that the third (rightmost) option is considered a bad practice . Another option not seen above is adding just shared_ptr with using std::shared_ptr directive.
The cstdlib in C++ library contains a superset of the traditional C functions, macros, and datatypes. An example of this is the set of absolute value (abs) functions that are declared. In stdlib.h, C defines the functions required to calculate the absolute values (abs) of an integer, long, or long long value. However, there is no provision for obtaining the absolute value of a float, double, or long double. These types are instead declared in math.h, which is another oft-used C header.
|Absolute value datatype||Function||C header|
|Integer||int abs(int x)||stdlib.h|
|Long integer||long labs(long x)||stdlib.h|
|Long long integer||long long llabs(long long x)||stdlib.h|
|Float||float fabsf(float x)||math.h|
|Double||double fabs(double x)||math.h|
|Long double||long double fabsl(long double x)||math.h|
Figure 2 : Absolute value functions in the C Standard Library
The relevant overrides for abs() within the cstdlib in C++ header cover all of the above cases.
The cstdlib in C++ header includes several member functions, datatypes, and constant values. The following tables describe what functions are defined by the header file.
|Conversion Functions||Description or Example|
|atof||Convert a string into a double. Note: The return result is NOT a float.|
|atoi||Converts a string into an integer.|
|atol||Converts a string into a long|
|The following functions are more robust alternatives to those above|
|strtod||Converts a string into a double.|
|strtol||Converts a string into a long integer.|
|stltoul||Converts a string into an unsigned long integer.|
|strtoll||Converts a string into a long long integer.|
|strtoull||Converts a string into an unsigned long long integer.|
Figure 3 : Conversion functions
|Random numbers||Description or Example|
|rand||Generates an pseudo-random integer|
|random||A non-standard C integer-returning function (provided by POSIX)|
|srand||Sets the random number generator’s seed value|
|srandom||Sets the random number generator’s seed (non-standard C, POSIX)|
Figure 4 : Random number-related functions
|Memory Allocation||Description or Example|
|malloc||Allocate memory from the heap (specify entire block size)|
|calloc||Allocate memory from the heap (specify size and count; initialize memory)|
|realloc||Adjust the size of memory that has already been allocated|
Figure 5 : Dynamic memory allocation functions
|Searching and Sorting||Description or Example|
|bsearch||Perform a binary searching on an array|
|qsort||Sort an array using Quick Sort|
Figure 6 : Searching and sorting functions
|Math Functions||Description or Example|
|abs||Calculate the absolute value of an integer|
|labs||Calculate the absolute value of a long integer|
|div||Perform integer division with quotient and remainder returned as the result|
|ldiv||Long integer division with quotient and remainder returned in the result|
Figure 7 : Mathematical functions
|Multibyte / Wide Character Functions||Description or Example|
|mblen||Return the size of a multibyte character|
|mbtowc||Convert a multibyte character to a wide character|
|wctomb||Convert a wide character to a multibyte character|
|mbstowcs||Convert sequence of multibyte characters to a sequence of wide characters|
|wcstombs||Convert sequence of wide characters to a sequence of multibyte characters|
Figure 8 : Functions for working with multibyte and wide characters
Constants and Macros
The cstdlib in C++ library contains a variety of macros and constants to assist with the standardization of C++ development and code bases. An example of this is the constant values used to return from the main function, as follows:
The EXIT_SUCCESS constant can be used as a return value from the main function that the calling framework will interpret as successful execution. Although the value zero also denotes a successful execution of the program, EXIT_SUCCESS is implementation-specific.
The EXIT_FAILURE constant is also used as a return value from the main function. However, it indicates to the calling framework that the execution failed, perhaps with a critical operating-system-level error.
Figure 11 : Examples of macros used to return from the main function
Other examples of constant values defined by cstdlib in C++ are NULL, which defines a null pointer constant, RAND_MAX, which is the maximum possible value generated by the rand command, and MB_CUR_MAX, which represents the maximum number of bytes in a multibyte character for the current locale.
The header of the general-purpose standard library for C++, also known as cstdlib in C++, defines a core set of functions used for data type conversion, pseudo-random number generation, memory allocation, searching, sorting, mathematics, and dealing with wide or multibyte characters. It also contains a variety of useful macros in the form of constant values. In many cases C++ programmers use types, functions or constants, that come from cstdlib, without having to include this header, as it is being included by other headers that they are using. Not being aware where some types and utilities come from may later lead to annoying compilation errors, when some previously included header is removed and some constatnt is surprisingly not recognized. Knowing that cstlib might be required can save some time in such cases.
An expert software developer and product strategist, Dori Exterman has 20 years of experience in the software development industry. As CTO of Incredibuild, he directs the company’s product strategy and is responsible for product vision, implementation, and technical partnerships. Before joining Incredibuild, Dori held a variety of technical and product development roles at software companies, with a focus on architecture, performance, advanced technologies, DevOps, release management and C++. He is an expert and frequent speaker on technological advancement in development tools.