Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

‘new’ object freed with ‘delete[]’

ID: cpp/new-delete-array-mismatchKind: problemSecurity severity: Severity: warningPrecision: highTags:   - reliabilityQuery suites:   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

This rule findsdelete[] expressions that are using a pointer that points to memory allocated using thenew operator. Behavior in such cases is undefined and should be avoided.

Thenew operator allocates memory for justone object, then calls that object’s constructor, anddelete does the opposite. The arraydelete[] operator, however, expects the pointer to be pointing to the first element of an array (which could have header data specifying the length of the array) and would attempt to call the destructor on each element of the ‘array’, which would likely lead to a segfault due to the invalid header data.

WARNING: This check is an approximation, so some results may not be actual defects in the program. It is not possible in general to compute the values of pointers without running the program with all input data.

Recommendation

Use thedelete operator when freeing memory allocated withnew.

Example

Record*ptr=newRecord(...);...delete[]ptr;// ptr was created using 'new', but was freed using 'delete[]'

References

  • S. Meyers.Effective C++ 3d ed. pp 73-75. Addison-Wesley Professional, 2005.


[8]ページ先頭

©2009-2025 Movatter.jp