Unprotected dynamic memory allocation
Pointer returned from dynamic allocation not checked for NULL
or
nullptr
value
Description
This defect occurs when you access dynamically allocated memory without first checking if the prior memory allocation succeeded.
Risk
When memory is dynamically allocated using malloc
,
calloc
, or realloc
, it returns a value
NULL
if the requested memory is not available. If the code
following the allocation accesses the memory block without checking for this
NULL
value, this access is not protected from
failures.
Fix
Check the return value of malloc
, calloc
, or
realloc
for NULL before accessing the allocated memory
location.
int *ptr = malloc(size * sizeof(int)); if(ptr) /* Check for NULL */ { /* Memory access through ptr */ }
Examples
Result Information
Group: Dynamic memory |
Language: C | C++ |
Default: Off |
Command-Line Syntax: UNPROTECTED_MEMORY_ALLOCATION |
Impact: Low |
Version History
Introduced in R2013b
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)