The malloc
, realloc
, calloc
and free
routines are used to dynamically allocate memory in the
heap. But, in contrast to the new
and delete
operators introduced in C++, they allocate raw memory, which is not type-safe,
and they do not correctly invoke object constructors. Additionally, mixing them with new
/delete
results in undefined
behavior.
Note that directly replacing those functions with new
/delete
is usually not a good idea (see S5025).
Noncompliant code example
string* pStringArray1 = static_cast<string*>(malloc(10 * sizeof(string))); // Noncompliant
Person *p = (Person*)malloc(sizeof(Person)); // Noncompliant
Compliant solution
std::array<string, 10> stringArray1 ; // Compliant, use std::vector instead if the size is dynamic
auto p1 = new Person("Bjarne"); // Compliant, but don't do that, prefer the version on next line
auto p2 = std::make_unique<Person>("Bjarne"); // Compliant