C allocation function used in C++ code
ID |
c.maintainability.c_memory_allocation_in_cpp |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Resource Management |
Language |
C / C++ |
Description
This C++ file allocates memory with malloc/calloc/realloc/free. These functions do not run constructors or destructors, so using them on a non-trivial type produces uninitialized objects or leaks resources those objects own, and mixing them with new/delete on the same pointer is undefined behavior. Prefer std::make_unique/std::make_shared, a standard container, or plain new/delete when a container is not appropriate.
Rationale
This C++ file allocates memory with malloc/calloc/realloc/free. These functions do not run constructors or destructors, so using them on a non-trivial type produces uninitialized objects or leaks resources those objects own, and mixing them with new/delete on the same pointer is undefined behavior. Prefer std::make_unique/std::make_shared, a standard container, or plain new/delete when a container is not appropriate.
The following code illustrates the pattern detected by this rule:
void legacy(int n)
{
// FLAGGED: C allocation function used in C++ code
int *p = (int *)malloc(sizeof(int) * n);
// FLAGGED: C allocation function used in C++ code
int *q = (int *)calloc(n, sizeof(int));
// FLAGGED: C allocation function used in C++ code
q = (int *)realloc(q, 2 * n * sizeof(int));
// FLAGGED: C allocation function used in C++ code
free(p);
// FLAGGED: C allocation function used in C++ code
free(q);
}