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

            Bug ID: 42561
           Summary: Incorrect optimization of unique_ptr construction
                    leads to segfault
           Product: clang
           Version: 8.0
          Hardware: PC
                OS: Linux
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: C++
          Assignee: unassignedclangb...@nondot.org
          Reporter: jas...@3db-labs.com
                CC: blitzrak...@gmail.com, dgre...@apple.com,
                    erik.pilking...@gmail.com, llvm-bugs@lists.llvm.org,
                    richard-l...@metafoo.co.uk

This comes from a Stack Overflow question I asked a long time ago:

https://stackoverflow.com/questions/43624400/is-this-unsafe-usage-of-a-braced-initializer-list-in-a-range-based-for-loop

A minimal test case is as follows:

----------

#include <initializer_list>
#include <memory>

struct Test
{
    int x;
};

int main()
{
    std::unique_ptr<Test> a(new Test);
    std::unique_ptr<Test> b(new Test);
    std::unique_ptr<Test> c(new Test);
    int id = 0;
    for(auto t : std::initializer_list<Test*>({a.get(), b.get(), c.get()}))
        t->x = id++;
    return 0;
}

----------

I compiled the above code with "-O3 -std=c++11". What I'm seeing is that,
since, clang v3.9, the above program crashes with a segfault pn my x86_64
system. From looking at the assembly that is generated, it appears that the
construction of the std::unique_ptr objects is optimized out, but the for loop
that dereferences the unique_ptr objects is not elided. Thus, an uninitialized
pointer is dereferenced and a segfault ensues.

I have the example code up on Compiler Explorer to show how the compiler output
evolves between clang versions:

https://gcc.godbolt.org/z/_7MK9z

It appears to work properly with versions before v3.9 (in which case it
optimizes out the entire program, which is reasonable).

-- 
You are receiving this mail because:
You are on the CC list for the bug.
_______________________________________________
llvm-bugs mailing list
llvm-bugs@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to