Main Content

AUTOSAR C++14 Rule A18-5-9

Custom implementations of dynamic memory allocation and deallocation functions shall meet the semantic requirements specified in the corresponding "Required behaviour" clause from the C++ Standard

Since R2020b

Description

Rule Definition

Custom implementations of dynamic memory allocation and deallocation functions shall meet the semantic requirements specified in the corresponding "Required behaviour" clause from the C++ Standard.

Rationale

The C++ Standard ([new.delete]) specifies certain required behaviors for the dynamic allocation and deallocation functions. If you implement a global replacement allocation or deallocation function that does not meet these semantic requirements, other functions that rely on the required behaviors might behave in an undefined manner.

For instance, void* operator new ( std::size_t count ) is expected to throw a bad_alloc exception if it fails to allocate the requested amount of memory. If you implement a replacement allocation function that returns nullptr instead of throwing, a function that expect the memory allocation to throw on failure might try to dereference a null pointer instead.

Polyspace Implementation

Polyspace® flags these replacement implementations of dynamic allocation and deallocation functions.

  • Replacement operator new that returns nullptr when the expected behavior is to throw a bad_alloc exception on failure.

  • Replacement operator new or operator delete that throw directly or indirectly on failure when the expected behavior is to not throw. Polyspace also highlights the location of the throw in your code.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include<new>

extern void* custom_alloc(std::size_t);

void* operator new (std::size_t count) //Non-compliant
{
    return custom_alloc(count);
}

void func()
{
    int* ptr1;
    try {
        ptr1 = new int;
    } catch (const std::bad_alloc&) {
        //handle exception
    }

    //Use ptr1

}

In this example, the custom allocation function custom_alloc, which is defined elsewhere, might return nullptr on failure. Function func, which expects a bad_alloc exception if the memory allocation fails, might dereference a null pointer because operator new does not throw.

Check Information

Group: Language support library
Category: Required, Automated

Version History

Introduced in R2020b