On a recent bug hunt, I found an issue with returning a pointer to a member of a temporary variable. The offending (simplified) code was:
struct S {
S(int i) : i(i) {}
int i;
int* ptr() { return &i; }
};
int* fun(int i) { return S(i).ptr(); } // temporary S dies but pointer lives on
int main() {
int* p = fun(1);
return *p; // undefined
}
How to prevent this? GCC & Clang have -Waddress-of-temporary
and -Wreturn-stack-address
but they seem to loose trail because of ptr()
acting as a middle man for the dirty deeds. They are only triggered when the pointer is taken directly:
int* fun(int i) { return &S(i).i; } // rightly fails to compile
My project also incorporates cppcheck in continuous integration but it also can't pick it up (raised here).
Which static analysis tool can prevent this class of bugs?
EDIT: GCC does pick it up since version 6.1.0 with -Wreturn-local-addr
and (surprisingly) -O2
switched on.
-O2
, gcc catches this bug: melpon.org/wandbox/permlink/KaXY4ktTM1vMNTiX – Salta-O2
has nothing to do with it but the version of GCC does (detects since 6.1.0). I can't use a GCC that new, but it's a good argument to troll our maintainers to switch to a newer one:) – Ghassan-O2
on wandbox. But It's still a good idea to update :) – Saltaint* ptr() & { return &i; }
works in your specific case, but you can easily get the issue back by doingint* fun(int i) { S s{i}; return s.ptr(); }
. – Lailalain-O2
before 6.1.0, though). Come to think again... why would an optimization switch influence static analysis? I may file a bug for GCC:) – Ghassanfun
function, the compiler won't check the function and assume that it return a pointer that do not depend on the object. With optimization, the compiler would do inlining and see it as it would be a single function. With external function, it would not be able to do the check (at least without global analysis). – Limekiln