Invalid deletion of pointer
Pointer deallocation using delete
without
corresponding allocation using new
Description
This defect occurs when:
You release a block of memory with the
delete
operator but the memory was previously not allocated with thenew
operator.You release a block of memory with the
delete
operator using the single-object notation but the memory was previously allocated as an array with thenew
operator.
This defect applies only to C++ source files.
Risk
The risk depends on the cause of the issue:
The
delete
operator releases a block of memory allocated on the heap. If you try to access a location on the heap that you did not allocate previously, a segmentation fault can occur.If you use the single-object notation for
delete
on a pointer that is previously allocated with the array notation fornew
, the behavior is undefined.
The issue can also highlight other coding errors. For instance, you perhaps wanted
to use the delete
operator or a previous new
operator on a different pointer.
Fix
The fix depends on the cause of the issue:
In most cases, you can fix the issue by removing the
delete
statement. If the pointer is not allocated memory from the heap with thenew
operator, you do not need to release the pointer withdelete
. You can simply reuse the pointer as required or let the object be destroyed at the end of its scope.In case of mismatched notation for
new
anddelete
, correct the mismatch. For instance, to allocate and deallocate a single object, use this notation:classType* ptr = new classType; delete ptr;
To allocate and deallocate an array objects, use this notation:
classType* p2 = new classType[10]; delete[] p2;
If the issue highlights a coding error such as use of delete
or
new
on the wrong pointer, correct the error.
Examples
Result Information
Group: Dynamic memory |
Language: C++ |
Default: On for handwritten code, off for generated code |
Command-Line Syntax: BAD_DELETE |
Impact: High |
Version History
Introduced in R2013b
See Also
Find defects (-checkers)
| Invalid free of pointer
| Memory leak
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)