Search code examples
c++g++-5

Why does access a pointer in a union this way cause segmentation fault?


Why does the following code cause segmentation fault?

#include <string>

union U {
    bool boolean;
    double number;
    std::string* str_ptr;
};

int main()
{
    U u{new std::string("A")};
    delete u.str_ptr;
    return 0;
    // return u.str_ptr->compare("A");
}

I should say that it does not seem to matter if I instead of the return statement try to access the pointer in some other way. E.g. replace delete u.str_ptr; return 0; with return u.str_ptr->compare("A"); I still get a segmentation fault.

In case this is compiler specific I am using g++ (Ubuntu 5.4.0-6ubuntu1~16.04.2) 5.4.0 20160609


Solution

  • It is not legal to access u.str_ptr unless it was the last member set in the union. But the last member set in the union is boolean, since an initializer list with one undesignated value sets the first member.

    See "member lifetime" under struct and union initialization.