Pointer deallocation using delete without
corresponding allocation using new
This defect occurs when:
You release a block of memory with the delete operator
but the memory was previously not allocated with the new
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 the new operator.
This defect applies only to C++ source files.
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 for
new, 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.
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 the new operator, you do
not need to release the pointer with delete. 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 and
delete, 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.
| Group: Dynamic memory |
| Language: C++ |
| Default: On for handwritten code, off for generated code |
Command-Line Syntax: BAD_DELETE |
| Impact: High |
| CWE ID: 404 |