llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
26.8k stars 10.98k forks source link

clang-analyzer-cplusplus.NewDeleteLeaks when a tuple of a unique_ptr is captured in lambda #56240

Open kanje opened 2 years ago

kanje commented 2 years ago

Observation

Both clang-tidy and scan-build warn about a potential memory leak in this code, which looks like a false positive:

#include <tuple>
#include <memory>

int main()
{
    auto lambda = [tuple = std::make_tuple(std::make_unique<int>(42))] {};
}
$ clang-tidy main.cpp -checks="clang*"
1 warning generated.
/foo/main.cpp:7:1: warning: Potential leak of memory pointed to by field '_M_head_impl' [clang-analyzer-cplusplus.NewDeleteLeaks]
}
^
/foo/main.cpp:6:44: note: Calling 'make_unique<int, int>'
    auto lambda = [tuple = std::make_tuple(std::make_unique<int>(42))] {};
                                           ^~~~~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-redhat-linux/11/../../../../include/c++/11/bits/unique_ptr.h:962:30: note: Memory is allocated
    { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
                             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/foo/main.cpp:6:44: note: Returned allocated memory
    auto lambda = [tuple = std::make_tuple(std::make_unique<int>(42))] {};
                                           ^~~~~~~~~~~~~~~~~~~~~~~~~
/foo/main.cpp:7:1: note: Potential leak of memory pointed to by field '_M_head_impl'
}
^

Expected Behaviour

No warning is issued for this code.

Additional Details

Environment: Fedora 35, clang 13.0.0, gcc 11.3.1.

Compile commands:

[
{
  "directory": "/foo",
  "command": "/usr/bin/g++ -std=c++17 /foo/main.cpp",
  "file": "/foo/main.cpp"
}
]

Note, the issue is reproducible with -std=c++17 and -std=c++20, but not with -std=c++14.

kanje commented 2 years ago

Just have discovered https://github.com/llvm/llvm-project/issues/55219. So this probably is a duplicate.

llvmbot commented 2 years ago

@llvm/issue-subscribers-clang-static-analyzer

haoNoQ commented 1 year ago

Yes, it looks like we're having trouble modeling the effects of named captures :(