Frontend doesn't detect mismatching uses of 'new' and 'delete'. Analyzer catches this case.
Emit warning, and recover, when:
int *p = new int[1]; delete p; // treat as 'delete[]' int *l = new int(1); delete[] l; // treat as 'delete'
Paths
| Differential D4661
Detect mismatching 'new' and 'delete' uses ClosedPublic Authored by ismailp on Jul 24 2014, 2:27 PM.
Details
Summary Frontend doesn't detect mismatching uses of 'new' and 'delete'. Analyzer catches this case. Emit warning, and recover, when: int *p = new int[1]; delete p; // treat as 'delete[]' int *l = new int(1); delete[] l; // treat as 'delete'
Diff Detail Event Timelineismailp updated this object. Comment Actions This seems like a really nice idea.
ismailp edited edge metadata. Comment ActionsUpdated patch to address following issues:
Comment Actions
Comment Actions This is looking really good. Some fairly minor comments...
Comment Actions Addressed comments:
Comment Actions Addressed:
Comment Actions
rsmith edited edge metadata. Comment ActionsLGTM, thanks!
This revision is now accepted and ready to land.May 12 2015, 3:23 PM Closed by commit rL237368: Detect uses of mismatching forms of 'new' and 'delete' (authored by ismailp). · Explain WhyMay 14 2015, 9:18 AM This revision was automatically updated to reflect the committed changes.
Revision Contents
Diff 12356 include/clang/Basic/DiagnosticSemaKinds.td
include/clang/Sema/Sema.h
lib/Sema/Sema.cpp
lib/Sema/SemaExprCXX.cpp
test/Analysis/Malloc+MismatchedDeallocator+NewDelete.cpp
test/Analysis/MismatchedDeallocator-checker-test.mm
test/Analysis/MismatchedDeallocator-path-notes.cpp
test/CodeGenCXX/new.cpp
test/SemaCXX/delete.cpp
|
This is not a reasonable way to track the relevant state here.
The interesting cases are VarDecls and FieldDecls. For VarDecls, at the point where we see the delete, you can immediately check whether you have an new-expression as an initializer (and don't worry about the obscure cases where an initializer comes after the use). For FieldDecls, perform the check where you see the delete, and if you see either (a) no constructor with a matching new, or (b) only constructors with the wrong kind of new, then add your delete to a list to check at the end of the TU.
That way, in almost all cases we can deal with the diagnostic immediately rather than at end of TU. (This avoids building up a big set of all delete expressions.)
You'll also need to figure out how you're going to handle serialization/deserialization here, in the case where you hit one of these "not sure" cases in a PCH or similar. To that end, you should probably store a list of {SourceLocation, FieldDecl} pairs, or -- better -- a map from FieldDecl to the first source location where we saw a delete. (You'll need one extra bit to describe whether it was delete or delete[] I suppose...).