The following code produces a segmentation fault upon assignment to a union
member. This must be a result of misunderstanding unions, but I cannot pinpoint my error.
Q1: Is it necessary to include some initialization for the appropriate union member variables in T1's constructor?
I have tried something similar to the suggested solution (found in code block below) to initialize the appropriate member, but no success.
Q2: If T1 initialization is OK, why does assigning to this location produce a segmentation fault?
Relevant Code:
struct T1
{
T1(int type)
{
this->type = type;
//Q1 : need to init appropriate union struct here also? Something like:
/*
*if (type == 1)
*{
* union_member1.str = "";
*}
*else
*{
* union_member2.value = 0;
*}
*/
//If so, better alternative to this?
}
int type; //tells which union struct is used
union
{
struct //type 1
{
std::string str;
} union_member1;
struct //type 2
{
int value;
} union_member2;
};
};
struct T2
{
bool used;
/*
* other variables here
*/
};
std::map<std::string, T2> mymap;
T1* global_ptr;
int main()
{
for (auto& map_entry : mymap)
{
if (!(map_entry.second.used))
{
global_ptr = new T1(1);
global_ptr->union_member1.str = map_entry.first; //Q2: SEG fault occurs with this assignment
std::string s = map_entry.first; // but not with this assignment
}
}
}
GDB Output
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b70b03 in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_assign(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) ()
from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
Obviously, this code is shaved down for readability reasons. Map entries have been thoroughly validated, as well.
Aucun commentaire:
Enregistrer un commentaire