Wiki Markup |
---|
The return values for {{malloc()}} and other C memory allocation routines indicate the failure or success of the allocation. According to C99, {{calloc()}}, {{malloc()}}, and {{realloc()}} return null pointers if the requested memory allocation fails \[[ISO/IEC 9899:1999|AA. References#ISO/IEC 9899-1999]\]. Failure to detect and properly handle memory management errors can lead to unpredictable and unintended program behavior. As a result, it is necessary to check the final status of memory management routines and handle errors appropriately and in accordance with [ERR00-CPP. Adopt and implement a consistent and comprehensive error-handling policy]. |
By default operator new
will throw a std::bad_alloc
exception if the allocation fails. Therefore you need not check that the result of operator new
is NULL
. However, to ease conversion of code to C++, the C++ Standard ISO/IEC 14882-2003 provides a variant of operator new
that behaves like malloc()
:
...
When using std::nothrow
, it is imperative to check that the return value is not NULL
before using it.
The following table shows the possible outcomes of the C++ Standard Library memory allocation functions.
Function | Successful Return | Failure | |
---|---|---|---|
| pointer to allocated space | | |
| pointer to allocated space | | |
| pointer to the new object | | |
| pointer to allocated space | | N/A |
| pointer to allocated space | | N/A |
SettingAnchor 1 1 errno
is a POSIX ® extension to C99.
Noncompliant Code Example (malloc()
)
...