The use of dynamic memory can lead to out-of-storage run-time failures, which are undesirable.
The built-in new
and delete
operators, other than the placement versions, use dynamic heap memory. The functions
calloc
, malloc
, realloc
and free
also use dynamic heap memory.
There is a range of unspecified, undefined and implementation-defined behaviour associated with dynamic memory allocation, as well as a number of
other potential pitfalls. Dynamic heap memory allocation may lead to memory leaks, data inconsistency, memory exhaustion, non-deterministic behaviour,
etc.
Note that some implementations may use dynamic heap memory allocation to implement other functions (for example, functions in the library
cstring
). If this is the case, then these functions shall also be avoided.
Noncompliant code example
int *b;
void initialize()
{
b = (int*) malloc(1024 * sizeof(int)); // Noncompliant, could lead to an out-of-storage run-time failure.
if (b == 0)
{
// handle case when dynamic allocation failed.
}
}
Compliant solution
int b[1024]; // Compliant solution.