Expensive allocation in loop
Description
This defect occurs when these conditions are met:
The functions
malloc()
,calloc()
, oraligned_alloc()
is called inside a loop.The input for the memory allocating function is a fixed size.
The function
free()
is then called to deallocate that same memory inside the loop.
Risk
If the size of the memory is constant, allocating and deallocating memory in a loop is unnecessary and inefficient. Allocating the necessary memory once and deallocating the memory once at the end of all relevant operations is more efficient. Repeated allocation and deallocation of memory is inefficient and might lead to memory fragmentation and reduced performance.
Fix
Perform the memory allocation and deallocation outside of a loop when the memory size is constant. For instance, before entering the loop, allocate the required memory. Use the memory inside the loop. After the relevant operations are completed, deallocate the memory after the loop.
Performance improvements might vary based on the compiler, library implementation, and environment that you are using.
Examples
Result Information
Group: Performance |
Language: C | C++ |
Default: Off |
Command-Line Syntax:
EXPENSIVE_ALLOC_IN_LOOP |
Impact: Medium |
Version History
Introduced in R2022a
See Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)