Main Content

AUTOSAR C++14 Rule A18-5-1

Functions malloc, calloc, realloc and free shall not be used

Description

Rule Definition

Functions malloc, calloc, realloc and free shall not be used.

Rationale

C-style memory allocation and deallocation using malloc, calloc, realloc, or free is not type safe and does not invoke class's constructors/destructor to create/delete objects.

For instance, malloc allocates memory to an object and returns a pointer to the allocated memory of type void*. A program can then implicitly cast the returned pointer to a different type that might not match the intended type of the object.

The use of these allocation and deallocation functions can result in undefined behavior if:

  • You use free to deallocate memory allocated with operator new.

  • You use operator delete to deallocate memory allocated with malloc, calloc, or realloc.

The rule is not violated when you perform dynamic memory allocation or deallocation using overloaded new and delete operators, or custom implementations of malloc and free.

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 <cstdint>
#include <cstdlib>

void func()
{

    std::int32_t* p1 = static_cast<std::int32_t*>(malloc(sizeof(std::int32_t))); // Non-compliant
    *p1 = 0;

    free(p1); // Non-compliant

    std::int32_t* p2 = new std::int32_t(0); // Compliant

    delete p2; // Compliant
}

In this example, the allocation of memory for pointer p1 using malloc and the memory deallocation using free are non-compliant. These operations are not type safe. Instead, use operators new and delete to allocate and deallocate memory.

Check Information

Group: 18 Language Support Library
Category: Required, Automated

Version History

Introduced in R2019b