Segmentation fault while trying to change game state - c++

I'm making a state machine for switching game states (playing->menu->setup) in my game engine, but I'm getting a segmentation fault. I can change the game state fine from upper level, but how can I change the game state from within a game state?
Here's a minimal code example:
#include <iostream>
#include <vector>
class GameStateManager;
class GameState {
public:
GameState(GameStateManager* StateManager) {
StateManager = stateManager;
};
virtual ~GameState();
virtual void update() = 0;
GameStateManager* stateManager;
};
class GameStateManager {
public:
GameStateManager();
~GameStateManager();
void changeGameState(GameState* state) {
if(!running) {
running = true;
}
// Cleanup the current state
if(!gameStates.empty()) {
for(unsigned int i = 0; i < gameStates.size(); i++) {
delete gameStates[i];
}
gameStates.clear();
std::cout << "Cleaning up GameState" << std::endl;
}
// Store and initialize the new game state
gameStates.push_back(state);
};
void update() {
if(!gameStates.empty()) {
gameStates.back()->update();
}
};
std::vector<GameState*> gameStates;
bool running;
};
class PlayState : public GameState {
public:
PlayState(GameStateManager* stateManager) : GameState(stateManager) {};
~PlayState();
void update() override {
// On some flag, initiate the next level
nextLevel();
};
void nextLevel() {
stateManager->changeGameState(new PlayState(stateManager));
};
};
int main() {
GameStateManager stateManager;
stateManager.changeGameState(new PlayState(&stateManager));
while(stateManager.running) {
for(unsigned int i = 0; i < 10000; i++) {
std::cout << "Round: " << i << std::endl;
// Segmentation fault here
stateManager.update();
// This works
//stateManager.changeGameState(new PlayState(&stateManager));
}
stateManager.running = false;
}
return 0;
}

for some reason the stateManager is not being set in the GameState constructor.
so try this:
class GameState {
public:
GameState(GameStateManager* StateManager) : stateManager(StateManager)
{
};
virtual ~GameState();
virtual void update() = 0;
GameStateManager* stateManager;
};

Related

Return of function(vector) remains empty from static class

I have several singleton classes. Two of them each run as a separate thread. In one class, two vectors are filled and that works. If I now call the getPlayersEnemy function in the other class, the vector is always empty and I don't know why.
Player-Class:
#pragma once
#include <cstdint>
#include <string>
#include "Structs.h"
#include <vector>
class Player
{
private:
Player() {}
std::vector<entity> playersTeam;
std::vector<entity> playersEnemy;
int local = 0;
public:
static Player& getInstance()
{
static Player instance;
return instance;
}
void obtainPlayers();
std::vector<entity> getPlayersTeam();
std::vector<entity> getPlayersEnemy();
};
The two get*-Functions:
std::vector<entity> Player::getPlayersTeam()
{
return playersTeam;
}
std::vector<entity> Player::getPlayersEnemy()
{
return playersEnemy;
}
In the obtainPlayers function the vectors are getting filled(and also this is the function which runs in a thread)
Now, in the Categroize-Class, I init the Player class and call getPlayersTeam()/getPlayersEnemy():
#pragma once
#include "Game.h"
#include "Player.h"
class Categorize
{
private:
Categorize() {}
Memory& mem = Memory::getInstance();
Player& player = Player::getInstance();
Game& game = Game::getInstance();
public:
static Categorize & getInstance()
{
static Categorize instance;
return instance;
}
void run();
};
void Categorize::run()
{
while (true)
{
if (game.isFullyLoaded())
{
if (player.getPlayersEnemy().empty())
{
std::cout << "empty vector" << std::endl;
}
for (const entity ent : player.getPlayersEnemy())
{
std::cout << "called" << std::endl;
}
}
}
}
Here is where they're getting filled:
void Player::obtainPlayers()
{
while (true)
{
playersTeam.clear();
playersEnemy.clear();
Entity& ent = Entity::getInstance();
int localPlayer = ent.getLocalplayer();
if (!localPlayer)
{
continue;
}
std::cout << ent.getHealth(localPlayer);
playersTeam.push_back(
entity
{
localPlayer,
ent.getHealth(localPlayer),
true,
true,
true,
ent.getPosition(localPlayer)
}
);
int localPlayerTeam = ent.getTeam(localPlayer);
int team = 1;
int enemy = 0;
for (int i = 1; i < 64; i++)
{
int player = ent.getEntityByIndex(i);
if (player == localPlayer || !player)
{
continue;
}
if (ent.getTeam(player) == localPlayerTeam)
{
playersTeam.push_back(
entity{
player,
ent.getHealth(player),
ent.isDormant(player),
ent.isVisible(player, localPlayer),
ent.isSpotted(player),
ent.getPosition(player)
}
);
}
else
{
playersEnemy.push_back(
entity{
player,
ent.getHealth(player),
ent.isDormant(player),
ent.isVisible(player, localPlayer),
ent.isSpotted(player),
ent.getPosition(player)
}
);
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
}
Also the Categorize::run() is also running in another thread.
I don't know why the return of getPlayersEnemy()/getPlayersTeam() is always empty, where it is not, when I check in the player-class itslef.

Can't use vector of objects that use state machine pattern in c++

I want to make simple AI using FSM. When I simply make object it works perfectly fine but when I put them in vector it crashes after second update. Here is smallest code that shows this problem
class State
{
public:
virtual ~State() = default;
void setContext(Context* context);
virtual void processState() = 0;
protected:
Context* m_Context;
};
void State::setContext(Context* context)
{
m_Context = context;
}
class State1 : public State
{
public:
virtual void processState() override;
};
void State1::processState()
{
std::cout << "Processing State1" << std::endl;
m_Context->setState(new State2);
}
class State2 : public State
{
public:
virtual void processState() override;
};
void State2::processState()
{
std::cout << "Processing State2" << std::endl;
m_Context->setState(new State1);
}
class Context
{
public:
Context(State* state);
void update();
void setState(State* state);
private:
State* m_State;
};
Context::Context(State* state)
{
setState(state);
}
void Context::update()
{
m_State->processState();
}
void Context::setState(State* state)
{
delete m_State;
m_State = state;
m_State->setContext(this);
}
If I make it like this
Context context(new State1);
context.update();
context.update();
context.update();
context.update();
context.update();
it works and prints
Processing State1
Processing State2
Processing State1
Processing State2
Processing State1
but if I make it like this
std::vector<Context> contexts;
size_t amount = 1;
contexts.reserve(amount);
for (size_t i = 0; i < amount; i++)
{
Context context(new State1);
contexts.push_back(context);
}
for (size_t i = 0; i < amount; i++)
{
for (size_t j = 0; j < 5; j++)
{
contexts[i].update();
}
}
it only prints first state, crashes on second and gives this error code
Processing State1
-1073741819.
I tried to use break points but i still don't understand what's going on
You should consider using smart pointers or at least initiate the pointers to nullptr and check for this before calling delete.
The value of m_State is garbage, and in some cases you're calling delete on this unknown value - this results in an undefined behaviour and this is the reason that for some cases it works but for other it crashes.

When apply observer pattern an error occured

I have the following code:
class ISubscriber;
class News {
public:
float getVersion() { return this->version; }
void setVersion(float state) { this->version= state; this->notifyAllSubscribers(); }
void attach(ISubscriber *observer) { this->subscribers.push_back(observer); }
void notifyAllSubscribers() {
for (vector<ISubscriber*>::iterator it = subscribers.begin(); it != subscribers.end(); it++){
(*(*it)).update();
}
}
private:
vector<ISubscriber*> subscribers;
float version;
};
class ISubscriber {
public:
News *news;
virtual void update() = 0;
};
class Subscriber1 : public ISubscriber {
public:
Subscriber1(News *news) { this->news = news; this->news->attach(this); }
void update() override { cout << "Subscriber1: A new version of the newspaper has been launched (v" << this->news->getVersion() << ")" << endl; }
};
class Subscriber2 : public ISubscriber {
public:
Subscriber2(News *news) { this->news = news; this->news->attach(this); }
void update() override { cout << "Subscriber2: A new version of the newspaper has been launched (v" << this->news->getVersion() << ")" << endl; }
};
int main(int argc, char *argv[]) {
News newspaper;
newspaper.setVersion(2.1f);
Subscriber1 sb1(&newspaper);
Subscriber2 sb2(&newspaper);
return 0;
}
But strange errors happened:
The first error points to this code (*(*it)).update(); in news class.
Why that errors happened, what's the reason?
(*(*it)).update(); requires the type ISubscriber to be complete, just the forward declaration is not enough.
You could move the defnition of ISubscriber before the one of News, and give a forward declaration of News before that.
class News;
class ISubscriber {
public:
News *news;
virtual void update() = 0;
};
class News {
public:
float getVersion() { return this->version; }
void setVersion(float state) { this->version= state; this->notifyAllSubscribers(); }
void attach(ISubscriber *observer) { this->subscribers.push_back(observer); }
void notifyAllSubscribers() {
for (vector<ISubscriber*>::iterator it = subscribers.begin(); it != subscribers.end(); it++){
(*(*it)).update();
}
}
private:
vector<ISubscriber*> subscribers;
float version;
};

Accessing a pointer stored in a base class

I have a class called StateMachine, which controls all possible Entity States.
I then have a class called State which is a base class for unique Entity classes, e.g Attack State, Flee State.
When a new unique State is created (within the StateMachine), it passes in a StateMachine pointer, which will then be stored in the State base class, so that each unique State created can access its State Machine.
When I attempt to access the pointers members (using -> operator) it simple doesn't come up with any public methods, and I don't know why.
If anyone has any clue it would be greatly appreciated.
StateMachine.h
using STATE_PTR = std::shared_ptr<State>;
// Class to implement a finite state machine using the state desing pattern
class StateMachine
{
public:
StateMachine();
~StateMachine();
void OnEnter(STATE_NAME sn);
void OnExit();
void OnEvent(STATE_SYMBOL & ss);
void OnTick(float st);
void ChangeState(STATE_NAME const & sn);
void RegisterState(ENTITY_CLASS const & ec);
typedef std::map<STATE_NAME, STATE_PTR> STATE_REGISTRY;
private:
STATE_REGISTRY state_registry;
STATE_NAME current_state;
};
StateMachine.cpp
using namespace::std;
StateMachine::StateMachine()
: state_registry()
{
current_state = STATE_NAME::UNKNOWN;
}
StateMachine::~StateMachine()
{
state_registry.clear();
}
void StateMachine::OnEnter(STATE_NAME sn)
{
current_state = sn;
if (state_registry[current_state] != nullptr)
{
state_registry[current_state]->OnEnter();
}
}
void StateMachine::OnExit()
{
if (state_registry[current_state] != nullptr)
{
state_registry[current_state]->OnExit();
}
}
void StateMachine::OnTick(float st)
{
}
void StateMachine::OnEvent(STATE_SYMBOL & ss)
{
state_registry[current_state]->OnEvent(ss);
}
void StateMachine::RegisterState(ENTITY_CLASS const & ec)
{
switch (ec)
{
case ENTITY_CLASS::PLAYER_TANK :
state_registry.insert(std::make_pair(STATE_NAME::STATE_1, std::make_shared<PlayerTankState1>(this)));
state_registry.insert(std::make_pair(STATE_NAME::STATE_2, std::make_shared<PlayerTankState2>(this)));
break;
case ENTITY_CLASS::ENEMY_TANK :
state_registry.insert(std::make_pair(STATE_NAME::STATE_3, std::make_shared<EnemyTankState1>(this)));
state_registry.insert(std::make_pair(STATE_NAME::STATE_4, std::make_shared<EnemyTankState2>(this)));
state_registry.insert(std::make_pair(STATE_NAME::STATE_5, std::make_shared<EnemyTankState3>(this)));
break;
default:
break;
}
}
void StateMachine::ChangeState(STATE_NAME const & sn)
{
state_registry[current_state]->OnExit();
current_state = sn;
state_registry[current_state]->OnEnter();
}
State.h
class StateMachine; // Forward decloration of the StateMachine class
// Base class for all states of the game system
class State
{
protected:
State(StateMachine * p)
: mp_Owner(p)
{}
public:
virtual ~State() {}
virtual void OnEnter() = 0;
virtual void OnExit() = 0;
virtual void OnTick(float) = 0;
virtual void OnEvent(STATE_SYMBOL) = 0;
StateMachine * mp_Owner;
};
EnemyTankState.cpp (Unique State)
EnemyTankState1::EnemyTankState1(StateMachine * p)
: State(p)
{
}
EnemyTankState1::~EnemyTankState1()
{
}
void EnemyTankState1::OnEnter()
{
cout << "Hi From Enemy Tank: Partolling State" << endl;
}
void EnemyTankState1::OnExit()
{
cout << "Bye From Enemy Enemy Tank: Partolling State" << endl;
}
void EnemyTankState1::OnTick(float dt)
{
}
void EnemyTankState1::OnEvent(STATE_SYMBOL ss)
{
switch (ss)
{
// Takes Enemy Tank to Attacking State
case STATE_SYMBOL::SYMBOL_2 :
mp_Owner->
break;
}
}
Within the code sample above, the line mp_Owner-> is what is giving me grief, as it is not opening up a list of public methods as you would expect when using a class pointer.
Any help would be much appreciated. Sorry for the long chunks of code, I couldn't think of any other way of getting my problem across.

Inheritance container of Parent type cannot hold children?

I have a parent Menu class and children MainMenu, SettingsMenu, PauseMenu, etc.
I want to be able to hold them all in a vector...
I can do
std::vector<Menu*> myVector;
and then typecast each one when I push_back in the vector
pMainMenu = new MainMenu;
myVector.push_back((Menu*)pMainMenu);
and it compiles but something's not working right down the road...
It doesn't have to be a vector but I want to be able to iterate through them.
I'm always trying to implement the Observer pattern and I'm having difficulties with inheritance as well in that area!
For the Observer pattern I have an Observer class and Game inherits Observer. I have a Subject class inherited by InputComponent. Subject has a vector of Observer* called vObserver and a function called addObserver(Observer* observer) and adds the passed pointer in vObserver. I also have a function called Notify(event e), which iterates through vObserver and calls their onNotify functions.
So in Game, I have an InputComponent instance called inputComp. I do inputComp.addObserver(this) and inputComp.vObserver.size() is 1. Good. I have a call to Notify in InputComponent which does get triggered, but when it executes, the vObserver.size inside Subject is 0... idk what I'm doing wrong
EDIT:
class Menu
{
public:
virtual void draw() = 0;
virtual void onMouseMove(int x, int y) = 0;
virtual void onMouseButton(int button, bool is_down) = 0;
friend class InputComponent;
friend class MainMenuInputComponent;
protected:
SDL_Renderer* _renderer;
std::vector<Button> vButton;
std::vector<SDL_Texture *> vTexture;
};
class MainMenu : public Menu
{
public:
MainMenu(SDL_Renderer* renderer);
virtual void draw();
virtual void onMouseMove(int x, int y);
virtual void onMouseButton(int button, bool is_down);
friend class MainMenuInputComponent;
};
class InputComponent: public Subject
{
public:
virtual void processInput()
{}
static bool isMouseWithin(int mouseX, int mouseY, SDL_Rect rect)
{
if (mouseX >= rect.x && mouseX <= rect.x + rect.w && mouseY >= rect.y && mouseY <= rect.y + rect.h)
return true;
else
return false;
}
};
class MainMenuInputComponent : public InputComponent
{
public:
MainMenuInputComponent(MainMenu* owner)
:_owner(owner){}
virtual void processInput();
virtual void onBtnClick(std::string btnName);
MainMenu* _owner;
};
class Game : public Observer
{
public:
Game();
void initSDL();
void initGame();
void processGameInput();
void renderGame();
void update();
virtual void onNotify(Events e);
SDL_Window* myWindow;
SDL_Renderer* myRenderer;
std::vector<MainMenuInputComponent> vInputComponent;
std::stack<MainMenu*> menuStack;
};
Game::Game()
{
initSDL();
initGame();
}
void Game::initGame()
{
//Create the Main Menu
MainMenu* pMainMenu = new MainMenu(myRenderer);
//Add menu to the stack
menuStack.push((pMainMenu));
//Add it's components to respective arrays
MainMenuInputComponent inputComp = MainMenuInputComponent(pMainMenu);
vInputComponent.push_back(inputComp);
//Add Observer/Subject relationship.
inputComp.addObserver((Observer*)this);
int bob = (int)inputComp.vObserver.size(); //to see if size went up
}
void Game::processGameInput()
{
if (!menuStack.empty())
{
for (int i = 0; i < (int)vInputComponent.size(); i++)
{
//Menu* compOwner = (Menu*)(vInputComponent[i]._owner);
//std::unique_ptr<Menu, std::default_delete<Menu>> a = menuStack.top();
if ((vInputComponent[i]._owner) == menuStack.top())
{
vInputComponent[i].processInput();
}
//vInputComponent[i].processInput();
}
}
else
for (int i = 0; i < (int)vInputComponent.size(); i++)
{
vInputComponent[i].processInput();
}
}
void Game::renderGame()
{
SDL_RenderClear(myRenderer);
MainMenu* bob = menuStack.top();
if (!menuStack.empty())
(menuStack.top())->draw();
SDL_RenderPresent(myRenderer);
}
void Game::onNotify(Events event)
{
switch (event)
{
case POP_MENU:
menuStack.pop();
break;
case GOTO_SETTINGS:
//Menu* pSettingsMenu =(Menu*)(new SettingsMenu(myRenderer));
//menuStack.push(std::unique_ptr<Menu>(pSettingsMenu));
break;
// Handle other events, and update heroIsOnBridge_...
}
}
class Subject
{
public:
void addObserver(Observer* observer)
{
vObserver.push_back(observer);
}
void removeObserver(Observer* observer)
{
//vObserver.erase(std::find(vObserver.begin(), vObserver.end(), 8));
}
std::vector<Observer*> vObserver;
protected:
void notify(Events e)
{
for (int i = 0; i < (int)vObserver.size(); i++)
{
vObserver[i]->onNotify(e);
}
}
};
class Observer
{
public:
virtual ~Observer() {}
virtual void onNotify(Events e) = 0;
};
If MainMenu publically inherits from Menu, then you shouldn't even need to type cast the pointer to MainMenu to Menu at all. That is, this should work:
class Menu {};
class MainMenu : public Menu {};
std::vector<Menu*> myVector;
MainMenu* pMainMenu = // ...
myVector.push_back(pMainMenu);
However, what you really should be doing is using something like shared_ptr or unique_ptr. Here's a more complete example, using shared_ptr:
#include <vector>
#include <memory>
#include <iostream>
class Menu
{
public:
virtual void on_event() = 0;
// virtual destructor needed for polymorphic base classes
virtual ~Menu() {}
};
class MainMenu : public Menu
{
public:
virtual void on_event()
{
std::cout << "Hello world! from MainMenu" << std::endl;
}
};
class PauseMenu : public Menu
{
public:
virtual void on_event()
{
std::cout << "Hello world! from PauseMenu" << std::endl;
}
};
class SettingsMenu : public Menu
{
public:
virtual void on_event()
{
std::cout << "Hello world! from SettingsMenu" << std::endl;
}
};
int main()
{
std::vector<std::shared_ptr<Menu>> myVector;
myVector.push_back(std::make_shared<MainMenu>());
myVector.push_back(std::make_shared<PauseMenu>());
myVector.push_back(std::make_shared<SettingsMenu>());
for(auto& menu : myVector) {
menu->on_event();
}
return 0;
}
Expected output:
Hello world! from MainMenu
Hello world! from PauseMenu
Hello world! from SettingsMenu
This should also work and gives you the bonus feature of taking care of memory management for you.