Skip to content

Commit f02c86c

Browse files
authored
Merge pull request github#5726 from MathiasVP/fix-false-positive-in-return-stack-allocated-memory-2
C++: Fix false positive in return stack allocated memory (second attempt)
2 parents 897105d + 93e55e2 commit f02c86c

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

cpp/ql/src/Likely Bugs/Memory Management/ReturnStackAllocatedMemory.ql

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
import cpp
1515
import semmle.code.cpp.dataflow.EscapesTree
16+
import semmle.code.cpp.models.interfaces.PointerWrapper
1617
import semmle.code.cpp.dataflow.DataFlow
1718

1819
/**
@@ -39,6 +40,10 @@ predicate hasNontrivialConversion(Expr e) {
3940
e instanceof ParenthesisExpr
4041
)
4142
or
43+
// A smart pointer can be stack-allocated while the data it points to is heap-allocated.
44+
// So we exclude such "conversions" from this predicate.
45+
e = any(PointerWrapper wrapper).getAnUnwrapperFunction().getACallToThisFunction()
46+
or
4247
hasNontrivialConversion(e.getConversion())
4348
}
4449

cpp/ql/test/query-tests/Likely Bugs/Memory Management/ReturnStackAllocatedMemory/test.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,3 +189,30 @@ int *&conversionInFlow() {
189189
int *&pRef = p; // has conversion in the middle of data flow
190190
return pRef; // BAD [NOT DETECTED]
191191
}
192+
193+
namespace std {
194+
template<typename T>
195+
class shared_ptr {
196+
public:
197+
shared_ptr() noexcept;
198+
explicit shared_ptr(T*);
199+
shared_ptr(const shared_ptr&) noexcept;
200+
template<class U> shared_ptr(const shared_ptr<U>&) noexcept;
201+
template<class U> shared_ptr(shared_ptr<U>&&) noexcept;
202+
203+
shared_ptr<T>& operator=(const shared_ptr<T>&) noexcept;
204+
shared_ptr<T>& operator=(shared_ptr<T>&&) noexcept;
205+
206+
T& operator*() const noexcept;
207+
T* operator->() const noexcept;
208+
209+
T* get() const noexcept;
210+
};
211+
}
212+
213+
auto make_read_port()
214+
{
215+
auto port = std::shared_ptr<int>(new int);
216+
auto ptr = port.get();
217+
return ptr; // GOOD
218+
}

0 commit comments

Comments
 (0)