Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Updated, added table.

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

errno #1

malloc()

pointer to allocated space

NULL

ENOMEM

calloc()

pointer to allocated space

NULL

ENOMEM

realloc()

pointer to the new object

NULL

ENOMEM

operator new(size_t)

pointer to allocated space

bad_alloc

N/A

operator new(size_t, nothrow_t)

pointer to allocated space

NULL

N/A

  1. Anchor
    1
    1
    Setting errno is a POSIX ® extension to C99.

Noncompliant Code Example (malloc())

...