I have a case where I believe cppcheck assesses that a pointer (that gets returned) points to an object that will be destructed upon function exit, which it does not. Here is the sample case:
Also, it's quite odd that the error says I'm pointing to a local variable when it's actually pointing to the heap-allocated int returned by localPtr.get().
Out of curiosity, I created a behaviorally equivalent portion of code (confirmed by Compiler Explorer) that, oddly, does not reproduce the cppcheck error. This furthers my suspicion that this is a false positive. Here is the equivalent code that does not produce the same error:
// equivalentCase.cpp#include<memory>#include<vector>std::vector<std::unique_ptr<int>>intPtrs;int*storePtr(intnum){autolocalPtr=std::unique_ptr<int>(newint(num));int*ret=localPtr.get();intPtrs.push_back(std::move(localPtr));returnret;// no error here, or anywhere else}
I only changed how I defined localPtr. I hope this information helps in some way.
I understand the code is a little funky and that I could also use std::make_unique which would probably avoid the error. However, I am running into a case in my project where I am not using std::make_unique and I am instead constructing a std::unique_ptr from an existing pointer. Thanks!
Last edit: Muhammad Javed 2022-12-16
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
I have a case where I believe cppcheck assesses that a pointer (that gets returned) points to an object that will be destructed upon function exit, which it does not. Here is the sample case:
I run cppcheck on the file above and I get:
Also, it's quite odd that the error says I'm pointing to a local variable when it's actually pointing to the heap-allocated
int
returned bylocalPtr.get()
.Out of curiosity, I created a behaviorally equivalent portion of code (confirmed by Compiler Explorer) that, oddly, does not reproduce the cppcheck error. This furthers my suspicion that this is a false positive. Here is the equivalent code that does not produce the same error:
I only changed how I defined
localPtr
. I hope this information helps in some way.I understand the code is a little funky and that I could also use
std::make_unique
which would probably avoid the error. However, I am running into a case in my project where I am not usingstd::make_unique
and I am instead constructing astd::unique_ptr
from an existing pointer. Thanks!Last edit: Muhammad Javed 2022-12-16
Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/11439