简体   繁体   中英

Seg fault with default allocation std::set<void*>

I am trying to learn STL allocators for void*. Here is my code

#include <set>
#include <memory>

class Test {
 public:
    std::set<void*> GetAllInformation() { return info_set_; }

 private:
    std::set<void*> info_set_;
};

int main() {
    std::unique_ptr<Test> test_obj_;

    const auto info = test_obj_->GetAllInformation();
    if (info.empty())
        std::cout << "info empty";

    return 0;
}

But I am getting Segmentation fault at

Thread 1 received signal SIGSEGV, Segmentation fault.

0x00402a18 in std::_Rb_tree<void*, void*, std::_Identity<void*>, std::less<void*>, std::allocator<void*> >::_M_root (this=0x0) at C:/Program Files (x86)/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/bits/stl_tree.h:733

The stl_tree.h

      _Const_Base_ptr
      _M_root() const _GLIBCXX_NOEXCEPT
      { return this->_M_impl._M_header._M_parent; }

could anyone help to explain? Thanks

The problem is that currently test_obj_ is not pointing to any Test object. Thus the expression test_obj_->GetAllInformation() leads to undefined behavior .

Undefined behavior means anything 1 can happen including but not limited to the program giving your expected output. But never rely (or make conclusions based) on the output of a program that has undefined behavior.

So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash (which is what happens in your case).

For example, here the program doesn't crash but here it crashes.

So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.


1 For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM