Recommended Posts

Hello, I'm having a rather strange bug. I'm making puzzle game.

When the game starts(PlayState) for the first time  pieces are indeed correctly placed, but after that sometimes they appear fine and most of the time only half of each piece is present ( I'm composing them out of 2 rectangles). The other parts appear at coordinates like this : Part2: X[1] : 842150923, Y[1]: 842150691. It happens even if I don' t use rand().

I'm using a state machine:

PlayState can go to:

    - pause state

PauseState can go to:

 - Resume

- Main Menu stateMain

MenuState can go to:

- PlayState

- Exit

I'm following a  book "SDL Game Development" by Shaun Mitchell (btw It's full of bugs).

bool PlayState::onEnter() {
  
    int left_x = 600 + (rand() % static_cast<int>(750 - 600 + 1));
    int left_y = 500 + (rand() % static_cast<int>(500 - 100 + 1));
    Vec2 dimension = Vec2(100, 200);
    int right_x = left_x + 100;
    int right_y = left_y;
    Vec2 dimension_2 = Vec2(100, 200);
    SDL_Color color1 = { 255, 0, 0, 0 };
    Piece* piece = new Piece(Vec2(left_x, left_y), Vec2(right_x, right_y), dimension, dimension_2, color1);
  // Piece 2
    int i_left_x = 600 + (rand() % static_cast<int>(750 - 600 + 1));
    int i_left_y = 500 + (rand() % static_cast<int>(500 - 100 + 1));
    Vec2 dimension_i1 = Vec2(100, 100);
    int i_right_x = i_left_x;
    int i_right_y = i_left_y + 100;
    Vec2 dimension_i2 = Vec2(100, 100);
    SDL_Color color3 = { 0, 0, 255, 0 };
    Piece* piece3 = new Piece(Vec2(i_left_x, i_left_y), Vec2(i_right_x, i_right_y), dimension_i1, dimension_i2, color3);
  // and so on until I have 7 pieces.


}
// ...
void PlayState::update() {
    if (InputHandler::Instance()->isKeyDown(SDL_SCANCODE_ESCAPE)) {
        Game::Instance()->getStateMachine()->pushState(new PauseState());
    }

   for (unsigned int i = 0; i < m_pieces.size(); i++){
           m_pieces[i]->update();
}

The issue occurs when I go from  MainMenuState to PlayState after PauseState.

I'll provide additional  info if needed. Thanks in advance.

Edited by Dzuvan
Misspelled words

Share this post


Link to post
Share on other sites

Well I'm using constructor like this:

    Piece(): 
        m_position(Vec2(0,0)),m_position2(Vec2(0,0)),
        m_dimension(Vec2(0, 0)), m_dimension2(Vec2(0,0)), 
        offset(Vec2(0,0)), offset2(Vec2(0,0)) {}

My c++ is quite bad so I'm 100% missing something.

Share this post


Link to post
Share on other sites

Are you cleaning up your heap allocations when changing states, or preserving them for later? That could be causing some sort of issue, but it's hard to tell with the limited code posted. Try posting the other two states too? Also, why are you static casting an int to an int?

Share this post


Link to post
Share on other sites

Code you posted seems fine at first sight, 842150923 is 0x3232340b in hex, which is not near any limit. Since it's not happening at first, I am going with accessing non-existing data (eg accessing a piece after it got deleted).

For example, in your m_pieces vector, do you remove anything from it? If you do, do you delete the data (not related to this bug, but important to do right)? Do you ensure you cannot access that old data any more?

As a test, you could fill all values of a piece with a known and unused value just before you remove it, and then remove the piece (eg in a destructor). Since those values are in removed data, you should never find them in your live data. If you find those values in your live data, you know what the problem is. Sadly, if you don't find those values, it does not mean you don't have this problem.

Code-wise, how you remove and add a piece to m_pieces could be interesting, along with how you decide which elements contain live data, although your PlayState::update suggests everything in the vector is live data.

 

You could consider posting the code eg at github or some other site, which works better for larger code bases.

 

Edit: 842150691 is 0x32323323, which also has lots of 2 and 3s. Maybe it's text? http://www.asciitable.com/

thus  0x32323323 -> 32 32 33 23 -> "223#"

           0x3232340b -> 32 32 34 0b -> "224." (0b is not a printable character)

So yeah, garbage data you're reading, likely from a previous program that used that memory

 

Edited by Alberth

Share this post


Link to post
Share on other sites
1 hour ago, cmac said:

Are you cleaning up your heap allocations when changing states, or preserving them for later? That could be causing some sort of issue, but it's hard to tell with the limited code posted. Try posting the other two states too? Also, why are you static casting an int to an int?

Well I'm calling clear on vector that holds data.

bool PlayState::onExit() {
    for (unsigned int i = 0; i < m_pieces.size(); i++) {
        m_pieces[i]->clean(); // doesn't do anything. It's empty void function 
        m_pieces[i]->setOffset(Vec2(0, 0));
    }
    m_pieces.clear();
    std::cout<<"Exiting playState\n"<<std::endl;
    return true;

  
 // Here is state machine I'm Using 
  #include "InputHandler.h"

void GameStateMachine::pushState(GameState* pState) {
    m_gameStates.push_back(pState);
    m_gameStates.back()->onEnter();
}

void GameStateMachine::popState() {
    if (!m_gameStates.empty()) {
        if (m_gameStates.back()->onExit()) {
            delete m_gameStates.back();
            m_gameStates.pop_back();
        }
    }
}

void GameStateMachine::changeState(GameState* pState) {
    if (!m_gameStates.empty()) {
        if (m_gameStates.back()->getStateID() == pState->getStateID()) {
            return;
        }
        if (m_gameStates.back()->getIsValid()) {
            m_gameStates.back()->setIsValid(false); // Mark the state as invalid
        }
    }
    
    m_gameStates.push_back(pState);
    m_gameStates.back()->onEnter();
}

void GameStateMachine::update(){
    if (!m_gameStates.empty()) {
          m_gameStates.back()->update();
    }
}
void GameStateMachine::render() {
    if (!m_gameStates.empty()) {
        m_gameStates.back()->render();
    }
}

void GameStateMachine::dequeState() {
    if (!m_gameStates.empty()) {
        // If the state is invalid we proceed to dequeue the state
        if (!m_gameStates[0]->getIsValid() && m_gameStates[0]->onExit()) {
            delete m_gameStates[0];
            m_gameStates.erase(m_gameStates.begin());

            // Reset the Input handler buttons state
            // This line is extremely important, fixes an issue with the "State traveling"
            // when a button is in the position of another button in another state
            // this will prevent the accident of traveling 2 states with 1 click.
            InputHandler::Instance()->reset();
        }
    }
}
// Here is the call from MainMenuState 
  void MainMenuState::s_menuToPlay() {
    std::cout << "Play button clicked\n"<<std::endl;
    Game::Instance()->getStateMachine()->changeState(new PlayState());
}

bool MainMenuState::onExit() {
    for (unsigned int i = 0; i < m_buttons.size(); i++) {
        m_buttons[i]->clean();
    }
    m_buttons.clear();
    TextureManager::Instance()->clearFromTextureMap("playbutton");
    TextureManager::Instance()->clearFromTextureMap("exitbutton");

    std::cout << "Exiting menu state\n"<<std::endl;
    return true;
}

As for the static cast, I saw post on stackoverflow, since I thought rand was causing the issue. I changed that part of code.

Share this post


Link to post
Share on other sites

Read up on memory management; clearing the vector causes the pointer to go out of scope, but the data is never deleted, resulting in a memory leak.

Overall though read Alberth's post in detail, seems like he nailed the problem down.

Share this post


Link to post
Share on other sites
1 hour ago, Alberth said:

Code you posted seems fine at first sight, 842150923 is 0x3232340b in hex, which is not near any limit. Since it's not happening at first, I am going with accessing non-existing data (eg accessing a piece after it got deleted).

For example, in your m_pieces vector, do you remove anything from it? If you do, do you delete the data (not related to this bug, but important to do right)? Do you ensure you cannot access that old data any more?

As a test, you could fill all values of a piece with a known and unused value just before you remove it, and then remove the piece (eg in a destructor). Since those values are in removed data, you should never find them in your live data. If you find those values in your live data, you know what the problem is. Sadly, if you don't find those values, it does not mean you don't have this problem.

Code-wise, how you remove and add a piece to m_pieces could be interesting, along with how you decide which elements contain live data, although your PlayState::update suggests everything in the vector is live data.

 

You could consider posting the code eg at github or some other site, which works better for larger code bases.

 

Edit: 842150691 is 0x32323323, which also has lots of 2 and 3s. Maybe it's text? http://www.asciitable.com/

thus  0x32323323 -> 32 32 33 23 -> "223#"

           0x3232340b -> 32 32 34 0b -> "224." (0b is not a printable character)

So yeah, garbage data you're reading, likely from a previous program that used that memory

 

I do have code on github(I've fucked up code so many times in the past xD ) : https://github.com/Dzuvan/Puzzle

Well I'm gonna try to test it the way you described, thanks.

Yeah everything in that vector si live data. I'm only handling pieces in PlayState.

Share this post


Link to post
Share on other sites

Hi guys, I managed to fix the problem.

State machine was the culprit here. Changing state from pause to main menu didn't remove play state from stack. Once i  poped the  state while going to main menu problem went away.

Thank you all.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Announcements

  • Forum Statistics

    • Total Topics
      628402
    • Total Posts
      2982471
  • Similar Content

    • By RidiculousName
      So I have a class next semester where I need to learn C++. I'll be going through the class textbook too of course, but I hate textbooks because I learn much better by programming than taking notes. I understand there's got to be some reading just to understand the syntax, but I have trouble remembering much from a whole chapter before programming. I prefer to work with smaller bits of information and gradually expand.
      So my question is, how could I learn C++ in smaller bits?
    • By rXpSwiss
      Hello,
      I am sending compressed json data from the UE4 client to a C++ server made with boost.
      I am using ZLib to compress and decompress all json but it doesn't work. I am now encoding it in base64 to avoid some issues but that doesn't change a thing.
      I currently stopped trying to send the data and I am writing it in a file from the client and trying to read the file and decompress on the server side.
      When the server is trying to decompress it I get an error from ZLib : zlib error: iostream error
      My question is the following : Did anyone manage to compress and decompress data between a UE4 client and a C++ server ?
      I cannot really configure anything on the server side (because boost has its ZLib compressor) and I don't know what is wrong with the decompression.
      Any idea ?
      rXp
    • By glportal
      GlPortal is a free and open source first person 3D teleportation based puzzle game and platformer. But we have already integrated a physics engine and are planning for some physics based puzzles.
      We want to improve our Visual Studio support. Check out this project:
      https://github.com/kungfooman/glportal-vs
      You can chat with us on gitter https://gitter.im/GlPortal/glPortal
    • By noodleBowl
      So I have some quick questions about constructors and pointers

      Question on constructors:
      1. I'm working on this Sprite class and in general sprites need some kind of texture in order to display to the screen. So I have my class looking like this:
      class Sprite { public: Sprite(Texture* texture); ~Sprite(); Texture* texture; //Other class stuff } Now in the current state of my Sprite class would I be correct in that I cannot use it as a member in a different class, because it has no no-arg (default) constructor? That the only way this class could be a member is if it was a pointer?
      class SpriteContainer { public: SpriteContainer(); ~SpriteContainer(); Sprite singleSprite; //**BAD** not allowed because Sprite has no no-arg (default) constructor Sprite* singleSpritePtr; //This is allowed because its a pointer std::vector<Sprite> sprites; //**BAD** not allowed because Sprite has no no-arg (default) constructor std::vector<Sprite*> spites; //This is allowed because its a vector of Sprite pointers } I guess my really problem here is that I struggle with when a variable/class should be a pointer or not
      2. How do you make an abstract class where there are no methods that should be pure virtual functions?
      All the functions of the base class have there implementation, but I also do not want this class to be instantiated
      //Should not be able to instantiate this class. Should be an Abstract class class BaseClass { public: BaseClass() { x = 0; }; virtual ~BaseClass() { }; int x; void coolMethod() { ++x; } } //Can instantiate this class. coolMethod can be called from this class class DerivedClass : public BaseClass { public: DerivedClass(); ~DerivedClass(); }  
      Questions about smart pointers:
      1. I have never used these before, but are smart pointers ok when working with COM objects?
      Will the smart pointer automatically call a COM object's Release function or should I wrap my COM object and explicitly call Release in the wrapper class' destructor?
      2. Lets say there is a case where I wanted to give back the user of some APIs a pointer to a resource, but I also want them to know that they don't have to worry about cleaning it up. EG There is resource loader that will clean up all loaded resources once the program shuts down. The user has to do/worry about nothing.
      What type of smart pointer should I use in a case like this? Should it be a Shared pointer? Or should I make the resource a Unique pointer and then return to the user a raw pointer?
    • By Kazuma506
      I am trying to recreate the combat system in the game Life is Feudal but make it more complex. The fighting system works by taking in the direction of the mouse movement and if you press the left click it will swing in that direction, though stab, overhead, left (up, down, left right) and right are the only swings that you can do. If you wanted to you could also hold the swing by holding left click so you are able to swing at the perfect moment in the battle. I want to change this so add in more swing directions but I also want to code this from scratch in Unreal. Can anyone give me any pointers or maybe a few snippets of code that work in Unreal that could help me start to implement this type of system?
       
       
  • Popular Now