Search code examples
c++segmentation-faultinitializationdeclarationc++-chrono

C++ segmentation fault chrono


i am trying to create a little clock for my game-project. I am using the chrono-high-resolution-clock. However, after declaring the variable inside my header file "gameTime.hpp", when referencing it in my source-file "gameTime.cpp", i get a segfault. Hope anyone can help (and if the answer should be trivial: sorry, but the search i did on the subject didn't help me) Here is the code:

header-file:

class GameTime
{
private:
    std::chrono::high_resolution_clock::time_point mTime;
    std::chrono::high_resolution_clock::time_point mLastTime;
    double mTimeSpan;
public:
    GameTime();
    ~GameTime();
    void init();
    double timePassed();
};

Source-file:

GameTime::GameTime()
{

}

void GameTime::init()
{
    mTime = std::chrono::high_resolution_clock::now();
    mLastTime = std::chrono::high_resolution_clock::now();
}

double GameTime::timePassed()
{
    mTime = std::chrono::high_resolution_clock::now();
    mTimeSpan = std::chrono::duration_cast<std::chrono::milliseconds>(mTime - mLastTime).count();
    mLastTime = std::chrono::high_resolution_clock::now();

    return mTimeSpan;  
}

and the main-function: (it was pointed out that i should include this)

double frameTime;
GameTime* gameTime;

gameTime->init();

while(game->running())
{
    frameTime = gameTime->timePassed();

    std::cout << frameTime << std::endl;
}

The segfault happens inside the init() function, when i try to set a value for mTime. Thanks in advance!


Solution

  • okay, the problem was that in my main-function, i only created a pointer, but not a real instance of the class GameTime. The working code now looks like the following:

    (main.cpp)

    GameTime *gameTime = nullptr;
    
    int main()
    {
        gameTime = new GameTime();
    
        gameTime->init();
    
        while(game->running())
        {
            frameTime = gameTime->timePassed();
    
            std::cout << frameTime << std::endl;
        }
    
        return 0;
    }
    

    In my class-implementations, everything was fine.