[llvm-bugs] [Bug 44675] New: False positive on std::data(std::string&)

via llvm-bugs llvm-bugs at lists.llvm.org
Mon Jan 27 02:50:59 PST 2020


https://bugs.llvm.org/show_bug.cgi?id=44675

            Bug ID: 44675
           Summary: False positive on std::data(std::string&)
           Product: clang
           Version: 7.0
          Hardware: PC
                OS: Linux
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: Static Analyzer
          Assignee: dcoughlin at apple.com
          Reporter: cassio.neri at gmail.com
                CC: dcoughlin at apple.com, llvm-bugs at lists.llvm.org

The below presents 3 versions of a function named copy which attempts to get a
pointer to the first element of a string.

VERSION == 1: uses std::data(std::string&) and gives a false positive on "Use
of memory after it is freed"

VERSION == 2: uses str::string::data() and no warning is issued.

VERSION == 3: uses an inline copy-and-pasted implementation of libstdc++'s
std::data. Again, no warning is issued.

<FILE name="main.cpp">
        #include <string>
        #include <cstring>
        #include <iterator>

        namespace foo {

        // Copy-and-pasted from libstdc++
        template <typename _Container>
        constexpr auto
        data(_Container& __cont) noexcept(noexcept(__cont.data()))
        -> decltype(__cont.data())
        { return __cont.data(); }

        }

        #define VERSION 1

        void copy(std::string& tgt, char* src, unsigned n) {

                tgt.resize(n);

                #if VERSION == 1
                        std::memcpy(std::data(tgt), src, n); // scan-build:
warning: Use of memory after it is freed
                #elif VERSION == 2
                        std::memcpy(tgt.data(), src, n);     // scan-build: No
bugs found.
                #else
                        std::memcpy(foo::data(tgt), src, n); // scan-build: No
bugs found.
                #endif
        }

        void test(char* src, unsigned n) {
                std::string tgt;
                copy(tgt, src, n);
        }
</FILE>

Analysed with:
        $ scan-build clang++ -g -std=c++17 -c main.cpp -o main.o

FWIW:

a) Obviously, VERSION 2 is a good workaround. However, in my real code (not in
this self-contained, reduced test case) the function is a template on T and T
== std::string is just one possible instantiation. (Among others like
std::vector<char>, char[N], ... for which no warning is issued) Therefore,
fixing the false positive would be helpful to generic code.

b) In C++17 std::string::data returns char* in contrast to const char* as in
previous standards.

-- 
You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20200127/0c0b04d2/attachment.html>


More information about the llvm-bugs mailing list