struct Entry { int Int{}; }; struct Info { int* PInt{}; Entry* PSrc{}; }; Entry* GetEntry(); Info GetInfo() { Info info; info.PSrc = GetEntry(); if (info.PSrc) info.PInt = &info.PSrc->Int; return info; }
Output from "C:\Program Files\Cppcheck\cppcheck.exe" --inconclusive --enable=all foo.cpp:
"C:\Program Files\Cppcheck\cppcheck.exe" --inconclusive --enable=all foo.cpp
foo.cpp:43:10: error: Returning object that points to local variable 'PSrc' that will be invalid when returning. [returnDanglingLifetime] return info; ^ foo.cpp:41:17: note: Address of variable taken here. info.PInt = &info.PSrc->Int; ^ foo.cpp:31:10: note: Variable created here. Entry* PSrc{}; ^ foo.cpp:43:10: note: Returning object that points to local variable 'PSrc' that will be invalid when returning. return info;
Of course, there is no local variable PSrc...
Thanks! I have created ticket https://trac.cppcheck.net/ticket/10090
Thank you. The warning can be avoided if std::addressof() is used instead of &. Is cppcheck supposed to know std::addressof?
Log in to post a comment.
Output from
"C:\Program Files\Cppcheck\cppcheck.exe" --inconclusive --enable=all foo.cpp
:Of course, there is no local variable PSrc...
Last edit: CHR 2021-01-07
Thanks! I have created ticket https://trac.cppcheck.net/ticket/10090
Thank you. The warning can be avoided if std::addressof() is used instead of &. Is cppcheck supposed to know std::addressof?