I have a few classes that handle setting a player's chosen region in a game.
The Region class:
class Region
{
public:
string name;
Region(string n) : name(n) {}
}
The player controller class:
class PlayerController
{
public
Region* playerRegion
}
The RegionHandler class:
class RegionHandler
{
public:
enum RegionCode { EU, RU, SEA, AM, CH, AF};
PlayerController playerController;
vector<Region> regions;
RegionHandler() {
static const char *names[] = { "russia", "sea", "america", "china", "africa"};
for (auto n : names)
regions.emplace_back(n);
}
void chooseRegion() {
int playerRegionIndex;
cout << "Regions:\n"
<< "0. Europe\n"
<< "1. Russia\n"
<< "2. SEA\n"
<< "3. America\n"
<< "4. China\n"
<< "5. Africa\n";
do {
cout << "Select a region\n> ";
cin >> playerRegionIndex; // Get user to input a region int
}
while(playerRegionIndex < 0 || playerRegionIndex > 5);
playerController.playerRegion = ®ions[playerRegionIndex];
}
}
Main:
int main()
{
RegionHandler regionHandler;
PlayerController playerController;
regionHandler.chooseRegion();
string mystr = playerController.playerRegion->name;
}
But when I try to get the name of the region the player has chosen into a string or in cout which I should be able to do, I get a segmentation fault even though name is a public string which should be set in RegionHandler. I get no other errors and the program works fine otherwise.
The segmentation fault occurs after I enter a number for playerRegionIndex and is caused by string mystr = playerController.playerRegion->name;
I have never come across a segmentation fault before and I don't really understand the GDB output, which is why I am asking this.
Full source on GitHub
Compiled on the new Ubuntu Bash for Windows using g++ main.cpp -std=c++1y -o main -g
GDB Output:
Program received signal SIGSEGV, Segmentation fault.
0x00007f6f237ab45b in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
regionHandler.chooseRegion()
sets upregionHandler.playerController
. The local variable inmain
, also namedplayerController
, is unaffected, itsplayerRegion
member remains uninitialized, containing garbage. Also note that you have 6RegionCode
s but only 5 elements inregions
vector.