Exception Error while making a Clock/Timer class - c++

I am trying to make a Clock with the timeGetTime function and some others. But I keep getting an exception error. I know mayby the quality of the program is not really good, but I was just trying to get it work. It's supposed to be a singleton. I hope you can help me!
// The Clock header file
// The Clock API for meassuring time.
#include<Windows.h>
#include<WinBase.h>
#include<MMSystem.h>
class cTime
{
private:
double m_Ns;
double m_Ms;
double m_S;
public:
// Set Values
void SetN(double N) {m_Ns = N;}
void SetM(double M) {m_Ns = M;}
void SetS(double S) {m_Ns = S;}
// Get Values
double GetN() {return m_Ns;}
double GetM() {return m_Ms;}
double GetS() {return m_S;}
// GetTime functions
//int GetDiffrenceNs();
//int GetDiffrenceMs();
//int GetDiffrenceS();
};
class cClock
{
private:
cTime m_CurrentTime; // CurrentTime object
static cClock* m_pClock; // Pointer to only instance
cTime m_LastTime; // LastTime object
bool m_PerformanceCounter; // Set to true if the performance counter is available
double m_Frequency; // Tells the frequenty of the PerformanceCounter. The value that the PerformanceCounter will increase each second.
double m_CounterTime; // The Counter of the PerformanceCounter.
double m_Trillingstijd; // How long one count of the performance counter will take.
public:
static cClock* GetClock();
cTime CurrentTime(); // Get the CurrentTime.
cTime LastTime(); // Get the LastTime.
// Virtual destructor.
virtual ~cClock();
protected:
// Protected constructor.
cClock();
};
// The clock cpp file
#include "Clock.h"
cClock* cClock::m_pClock = 0;
cClock* cClock::GetClock()
{
//BOOL perf_flag; // Timer Selection Flag
//double time_factor; // Time Scaling Factor
//LONGLONG last_time; // Previous timer value
//LONGLONG perf_cnt;
if (QueryPerformanceFrequency((LARGE_INTEGER *) &m_pClock->m_Frequency))
{
QueryPerformanceCounter((LARGE_INTEGER *) &m_pClock->m_CounterTime);
m_pClock->m_PerformanceCounter = true;
m_pClock->m_Trillingstijd=1.0/m_pClock->m_Frequency;
double LastedSeconds = m_pClock->m_CounterTime/m_pClock->m_Frequency;
m_pClock->m_LastTime.SetN(LastedSeconds*1000000);
m_pClock->m_LastTime.SetM(LastedSeconds*1000);
m_pClock->m_LastTime.SetS(LastedSeconds);
}
else
{
m_pClock->m_PerformanceCounter = false;
double LastedMiliseconds = timeGetTime();
m_pClock->m_LastTime.SetN(LastedMiliseconds*1000);
m_pClock->m_LastTime.SetM(LastedMiliseconds);
m_pClock->m_LastTime.SetS(LastedMiliseconds/1000);
}
return cClock::m_pClock;
}
cTime cClock::LastTime()
{
return m_LastTime;
}
cTime cClock::CurrentTime()
{
if(m_PerformanceCounter)
{
QueryPerformanceCounter((LARGE_INTEGER *) &m_CounterTime);
double LastedSeconds = m_CounterTime/m_Frequency;
m_CurrentTime.SetN(LastedSeconds*1000000);
m_CurrentTime.SetM(LastedSeconds*1000);
m_CurrentTime.SetS(LastedSeconds);
}
else
{
int LastedMiliseconds = timeGetTime();
m_CurrentTime.SetN(LastedMiliseconds*1000);
m_CurrentTime.SetM(LastedMiliseconds);
m_CurrentTime.SetS(LastedMiliseconds/1000);
}
m_LastTime = m_CurrentTime;
return m_CurrentTime;
}
This is my main, really simple but I just tried to get it to work but it doesn't...
#include "Clock.h"
#include<iostream>
using namespace std;
int main()
{
cClock* Clock = cClock::GetClock();
cTime Test = Clock->CurrentTime();
cout << Test.GetN();
cout << Test.GetM();
cout << Test.GetS();
int temp;
cin >> temp;
return 0;
}

It seems that the method cClock* cClock::GetClock() uses m_pClock without initializing it (it is still 0).

You are never creating an instance of cClock, just accessing a null pointer to one.
If you really think a singleton is a good idea, then cClock::GetClock() will have to create one if it doesn't already exist; along the lines of
cClock* cClock::GetClock()
{
if (!m_pClock) {
m_pClock = new cClock;
}
// remainder of function
return m_pClock;
}
Note that this isn't thread-safe, and also introduces a memory leak. Singletons are difficult to implement in C++, and best avoided unless there is a genuine reason for wanting one. I would move the logic of GetClock() into a public constructor, and allow client code to create and destroy clock objects as it sees fit.

Related

C++ (Arduino), Can't update object when accessing it as attribute of another object

I have recently bought an Arduino which uses C++ to code on. I am familiar with Java and as C++ allows OO programming I didn't think it would have been that difficult. But...
CODE:
// LEDCLOCK CLASS /////////////////////////////////////////////////////////////////////////
class LedClock{
private:
int hours;
int minutes;
int seconds;
static const long secondInterval = 1000;
unsigned long previousMilliseconds;
unsigned long currentMilliseconds;
public:
LedClock(){
hours = 0;
minutes = 0;
seconds = 0;
previousMilliseconds = 0;
currentMilliseconds = 0;
};
int getHours(){
return hours;
};
int getMinutes(){
return minutes;
};
int getSeconds(){
return seconds;
};
long getSecondInterval(){
return secondInterval;
};
unsigned long getPreviousMilliseconds(){
return previousMilliseconds;
};
void setHours(int h){
if(h < 24 && h >= 0){
hours = h;
}else{
hours = 0;
}
};
void setMinutes(int m){
if(m < 60 && m > 0){
minutes = m;
}else{
minutes = 0;
}
};
void setSeconds(int s){
if(s < 60 && s > 0){
seconds = s;
}else{
seconds = 0;
}
};
void setPreviousMilliseconds(unsigned long ms){
previousMilliseconds = ms;
};
void increaseOneHour(){
// as there is no day counter to increment atm this if-else statement is a bit useless.
// setHour(getHours() + 1) would have sufficed here with the current setter
if(getHours()==23){
setHours(0);
}else{
setHours(getHours() + 1);
}
};
void increaseOneMinute(){
if(getMinutes() == 59){
increaseOneHour();
setMinutes(0);
}else{
setMinutes(getMinutes() + 1);
}
};
void increaseOneSecond(){
if(getSeconds() == 59){
increaseOneMinute();
setSeconds(0);
}else{
setSeconds(getSeconds() + 1);
}
};
void tick(){
currentMilliseconds = millis();
if(currentMilliseconds - getPreviousMilliseconds() >= getSecondInterval()){
setPreviousMilliseconds(currentMilliseconds);
increaseOneSecond();
}
};
};
// LEDCLOCKCONTROLLER CLASS ////////////////////////////////////////////////////////////////
class LedClockController{
private:
LedClock ledClock;
int mode = 2;
public:
LedClockController(LedClock lc){
ledClock = lc;
};
LedClock getLedClock(){
return ledClock;
};
int getMode(){
return mode;
};
void setMode(int newMode){
mode = newMode;
};
};
// ARDUINO CODE /////////////////////////////////////////////////////////////////////////
LedClock lc = LedClock();
LedClockController lcc(lc);
void setup() {
Serial.begin(9600); //Begin serializer to print out value
}
void loop() {
//doesn't give me updated values
if(lcc.getLedClock().getPreviousMilliseconds()<63000){
Serial.println(lcc.getLedClock().getSeconds());
lcc.getLedClock().tick();
}
//does give me updated values
//commented out for now
/*
if(lc.getPreviousMilliseconds()<63000){
Serial.println(lc.getSeconds());
lc.tick();
}
*/
}
Q1:
I have difficulties to update attributes of my LedClock attribute in my Controller class.
When I target the LedClock by itself, everything runs fine but when I would update it via the Controller, then it wouldn't. In short, when getting the seconds in the first case, I could see the increment in values in the output. When I did the same thing but via the controller, the seconds stayed 0.
So I am missing something vital here. Can someone help/explain what I am missing?
Q2: Ideally I would want to create the LedClock object inside the constructor but didn't seem to find how to.
I tried things that could make sense but with the issues I have been having, I was holding off on this:
LedClockController lcc(LedClock lc());
LedClockController lcc(LedClock);
//would make sense to me, I noticed C++ doesn't use the 'new' keyword so have no idea how to do that then
LedClockController lcc(LedClock());
All of those ran into compilation issues so probably another important C++ thing that I haven't taken into account.
P.S. I have been noticing that there are some different views on getter and setters (accessing the attributes directly vs actual functions). I have been using the method I am used to (and were mentioned on W3schools) because I will rely on setting logic in 1 place.

Read Access Violation while trying to use variables through shared pointers

This is for my university coursework.
I have a class called timestep that is going to be used as a typical timer in a game engine to calculate frame times, etc, and an application class.
I'm struggling to get my head around shared pointers, but am required to use one to access the timestep class from the application class. It doesn't throw up errors until the program is running, at which point it prints my "PRE TIMER" log to the console, and throws an exception after reaching timer->setStart(), flags the line start = ..... in the setStart method, and says **this** was nullptr.
Timestep.h:
#pragma once
#include <chrono>
namespace Engine {
class Timestep {
private:
std::chrono::high_resolution_clock::time_point start;
std::chrono::high_resolution_clock::time_point end;
public:
Timestep();
void setStart();
void setEnd();
float getTimeSeconds() const;
float GetTimeMilliSeconds() const;
};
}
timestep.cpp:
#pragma once
#include "engine_pch.h"
#include "core/timestep.h"
namespace Engine {
Timestep::Timestep(){}
void Timestep::setStart() {
start = std::chrono::high_resolution_clock::now();
}
void Timestep::setEnd() {
end = std::chrono::high_resolution_clock::now();
}
float Timestep::getTimeSeconds() const {
std::chrono::duration<float> time = end - start;
return time.count();
}
float Timestep::GetTimeMilliSeconds() const {
std::chrono::duration<float, std::milli> time = end - start;
return time.count();
}
}
application.cpp:
#include "engine_pch.h"
#include "core/application.h"
namespace Engine {
Application* Application::s_instance = nullptr;
std::shared_ptr<Timestep> timer;
Application::Application()
{
if (s_instance == nullptr)
{
s_instance = this;
}
log::log();
LOG_INFO("Logger init success");
}
Application::~Application()
{
}
void Application::run()
{
LOG_INFO("PRE TIMER");
timer->setStart();
LOG_INFO("POST TIMER");
while (s_instance) {
timer->setEnd();
float a = timer->getTimeSeconds();
LOG_INFO("Time since last frame is {0}", a);
timer->setStart();
}
}
}
Apparently, your timer in application.cpp is not pointing to any instance of Timestep, incurring the nullptr error. Explained simply, your shared pointer was not initialized.
Assuming that you want a separate instance of Timestep for each instance of Application, maybe you could solve the issue by initializing your std::shared_ptr<Timestep> timer;
Instead of
std::shared_ptr<Timestep> timer;
Try
std::shared_ptr<Timestep> timer(new Timestep());

function parameters that are writeable only by the function itself - recursion counter

So I'm trying to write a recursive function that keeps track of how often it got called. Because of its recursive nature I won't be able to define an iterator inside of it (or maybe it's possible via a pointer?), since it would be redefined whenever the function gets called. So i figured I could use a param of the function itself:
int countRecursive(int cancelCondition, int counter = 0)
{
if(cancelCondition > 0)
{
return countRecursive(--cancelCondition, ++counter);
}
else
{
return counter;
}
}
Now the problem I'm facing is, that the counter would be writeable by the caller of the function, and I want to avoid that.
Then again, it wouldn't help to declare the counter as a const, right?
Is there a way to restrict the variable's manipulation to the function itself?
Or maybe my approach is deeply flawed in the first place?
The only way I can think of solving this, is to use a kind of "wrapper-function" that keeps track of how often the recursive function got called.
An example of what I want to avoid:
//inside main()
int foo {5};
int countToZero = countRecursive(foo, 10);
//countToZero would be 15 instead of 5
The user using my function should not be able to initially set the counter (in this case to 10).
You can take you function as is, and wrap it. One way I have in mind, which completely encapsulates the wrapping is by making your function a static member of a local class. To demonstrate:
int countRecursive(int cancelCondition)
{
struct hidden {
static int countRecursive(int cancelCondition, int counter = 0) {
if(cancelCondition > 0)
{
return countRecursive(--cancelCondition, ++counter);
}
else
{
return counter;
}
}
};
return hidden::countRecursive(cancelCondition);
}
Local classes are a nifty but rarely seen feature of C++. They possess some limitations, but fortunately can have static member functions. No code from outside can ever pass hidden::countRecursive an invalid counter. It's entirely under the control of the countRecursive.
If you can use something else than a free function, I would suggest to use some kind of functor to hold the count, but in case you cant, you may try to use something like this using friendship to do the trick:
#include <memory>
class Counter;
int countRecursive(int cancelCondition, std::unique_ptr<Counter> counter = nullptr);
class Counter {
int count = 0;
private:
friend int countRecursive(int, std::unique_ptr<Counter>);
Counter() = default; // the constructor can only be call within the function
// thus nobody can provide one
};
int countRecursive(int cancelCondition, std::unique_ptr<Counter> c)
{
if (c == nullptr)
c = std::unique_ptr<Counter>(new Counter());
if(cancelCondition > 0)
{
c->count++;
return countRecursive(--cancelCondition, std::move(c));
}
else
{
return c->count;
}
}
int main() {
return countRecursive(12);
}
You can encapsulate the counter:
struct counterRecParam {
counterRecParam(int c) : cancelCondition(c),counter(0) {}
private:
int cancelCondition;
int counter;
friend int countRecursive(counterRecParam);
};
Now the caller cannot modify the counter, and you only need to modify the function slightly:
int countRecursive(counterRecParam crp)
{
if(crp.cancelCondition > 0)
{
--crp.cancelCondition;
++crp.counter;
return countRecursive(crp);
}
else
{
return crp.counter;
}
}
And the implicit conversion lets you call it with an int
counterRecursive(5);
One way to do this is to use a functor. Here's a simple example:
#include <iostream>
class counter
{
public:
unsigned operator()(unsigned m, unsigned n)
{
// increment the count on every iteration
++count;
// rest of the function
if (m == 0)
{
return n + 1;
}
if (n == 0)
{
return operator()(m - 1, 1);
}
return operator()(m - 1, operator()(m, n - 1));
}
std::size_t get_count() const
{
return count;
}
private:
// call count
std::size_t count = 0;
};
int main()
{
auto f = counter();
auto res = f(4, 0);
std::cout << "Result: " << res << "\nNumber of calls: " << f.get_count() << std::endl;
return 0;
}
Output:
Result: 13
Number of calls: 107
Since the count is stored in the object itself, the user cannot overwrite it.
Have you tried using "static" counter variable. Static variables gets initialized just once, and are best candidates to be used as counter variables.

Double function segmentation fault on return to double

I have a double function
double Grid::getAverageNeighborhoodFitnessEvaluation(int agentPositionX, int agentPositionY)
{
GetNeighbourhood(agentPositionX, agentPositionY,neighborhoodEvaluations);
int neighborscount = 0;
double fitnesssum = 0;
double neighborfitness;
double value;
for (size_t i = 0; i < neighborhoodEvaluations.size(); ++i)
{
if ((*(neighborhoodEvaluations.at(i))) != NULL)
{
neighborfitness = (*(neighborhoodEvaluations.at(i)))->GetFitness();
if(neighborfitness<0)
neighborfitness=0;
fitnesssum+=neighborfitness;
neighborscount++;
}
}
value = fitnesssum/neighborscount;
return value;
}
GetNeighbourhood assigns an array of a defined type (Agent) to neighborhoodEvaluations
*(neighborhoodEvaluations.at(i)))->GetFitness(); returns a double that represents a value for that point in the array. These have all been used previously with no issues.
When called from my main (where RealX and RealY are two integers)
int currentFitness = getAverageNeighborhoodFitnessEvaluation(RealX,RealY);
always works
double currentFitness = getAverageNeighborhoodFitnessEvaluation(RealX,RealY);
causes Segmentation fault
Does anyone know what possibilities could result in this and/or what value an int can take but a double can't seem to?
So far i have traced the error to our Agent implementation
Agent.cpp
#include "Agent.h"
Agent::Agent(void)
{
m_age = 0;
m_fitness = -1;
}
Agent::~Agent(void)
{
}
int Agent::GetAge()
{
return m_age;
}
double Agent::GetFitness()
{
return m_fitness;
}
void Agent::IncreaseAge()
{
m_age++;
}
AgentType Agent::GetType()
{
return m_type;
}
Agent.h
#ifndef AGENT_H
#define AGENT_H
enum AgentType { candidateSolution, cupid, reaper, breeder};
class Agent
{
public:
Agent(void);
virtual ~Agent(void);
double GetFitness();
int GetAge();
void IncreaseAge();
AgentType GetType();
virtual void RandomizeGenome() = 0;
protected:
double m_fitness;
AgentType m_type;
private:
int m_age;
};
#endif // !AGENT_H
Can't seem to locate the exact problem though
From your comment on the gdb debugger answer, I see that you are calling the GetFitness method on a null object (Agent::GetFitness (this=0x0)). This means that neighborhoodEvaluations.at(i) is returning a null-pointer. at() only checks for out of bounds, but if what was put into the array to begin with is a null pointer, at() won't help you. To guard agains this, you should change
if ((*(neighborhoodEvaluations.at(i))) != NULL)
into
if (neighborhoodEvaluations.at(i) != NULL)
If neighborhoodEvaluations is not supposed to contain null pointers, you will have to track down why getNeighborhood() is putting them there. Perhaps you are looking for out-of-bound neighbors for the elements at the edge of your set of points?
Quickly get started on gdb debugger using this article http://www.cs.cmu.edu/~gilpin/tutorial/ . Then tell us which line produces the segmentation fault .

C++ Struct defined data passing. Simple answer im sure

I am sure this is a very simple fix and I feel dumb asking it but here it goes.
I need help with a struct and passing info from a gather function to a save or set function, and then passing it again to another function for further use.
Basically, it looks like this to start. I'll just add short snips of the code. All can be provided if you would like to see it.
I right now am just looking for the proper way to pass struct defined data from get.... to set.... functions.
struct printype
{
char dots[8][15];
int unknown15; // can have values of 0..127
string serial11_14; // 8 characters 00000000...99999999
int year8; // without century, 0..99
int month7; // 1..12
int day6; // 1..31
int hour5; // 0..23
int minute2; // 0..59
};
int getunknown15(); // prototypes
int setunknown15(int);
then we have a simple main.
int main()
{
printype pt;
pt.unknown15=getunknown15();
pt.unknown15=setunknown15(12);
pt.serial11_14=getserial11_14();
pt.serial11_14=setserial11_14("12345678");
pt.year8=getyear8();
pt.year8=setyear8(44);
pt.month7=getmonth7();
pt.month7=setmonth7(11);
pt.day6=getday6();
pt.day6=setday6(12);
pt.hour5=gethour5();
pt.hour5=sethour5(12);
pt.minute2=getminute2();
pt.minute2=setminute2(23);
cout <<"-----------------------------------------------------"<<endl;
cout <<" Let's Get Started"<<endl;
cout <<"-----------------------------------------------------"<<endl;
setup(pt.dots); // sets up the array
dpinfo(pt); // prints out the final array
ftarray(pt);
spar(pt.dots);
darray(pt.dots);
}
and finally the get and set array functions.
int getunknown15()
{
printype tem;
cout <<"-----------------------------------------------------"<<endl;
cout <<" Enter the Unkown Variable (0-127): ";
cin >>tem.unknown15;
cout <<"-----------------------------------------------------"<<endl;
return tem.unknown15;
}
next is
int setunknown15(int tem)
{
printype pp;
if (tem>127||tem<0)
{
cout << "Error" << endl;
return 0;
}
else
{
pp.unknown15 = tem;
return pp.unknown15;
}
}
I hope this isn't too much to read and understand
Anyway, I know this has a really simple answer but my brain just isn't working right now.
Edit: As StilesCrisis stated, Send struct as parameter is quiet stupid in this case. better use a const reference.
Well, I am not sure if I understand your question correctly. You can simply send struct to another function as parameter, or as a pointer.
like:
void SetStruct(const printype& var);
printype GetStruct();
Is it what you are looking for?
Please use the following access to the your fields, (by reference):
struct printype *myPtr = new printype;
myPtr->day6 = 43;
When use pointer instead of a normal variable, you should use -> instead . to access your fields.
I know this is kind of old but I thought I should give it a shot, since you are using C++ and it looks like you are trying to use some OO practices (I think), you don't need to start with a struct, even though OO principles can be applied using them as well though not as elegantly.
you can define your class header file as such.
#ifndef PRINTYPE_H
#define PRINTYPE_H
#include <string>
using namespace std;
class printype
{
private: // we always want to declare our member fields private for safety/managements reasons, no one will be able to access them outside.
char dots[8][15];
int unknown15; // can have values of 0..127
string serial11_14; // 8 characters 00000000...99999999
int year8; // without century, 0..99
int month7; // 1..12
int day6; // 1..31
int hour5; // 0..23
int minute2; // 0..59
void init(); // This is the method we use to initialize our starting state.
public: // This is our public methods, how people deal with/get/set our state.
printype(); // This is our default constructor
printype(const printype& print_type); // This our copy constructor
virtual ~printype(); // This is our destructor, its virtual, making safer for inheritance.
// This is our setters/getters
void setUnknown(int unknown);
int getUnknown();
void setYear(int year);
int getYear();
void setMonth(int mont);
int getMonth();
// and well you get the idea, you can add more methods.
};
#endif
and the accompanying class source file with your functions implementation
printype::printype()
{
this->init(); // Initialize all your vatiables, safer to just define a function to this.
}
printype::printype(const printype& orig) // copy constructor
{
this->setUknown(orig.getUnknown());
this->setDay(orig.getDay());
this->setDots(orig.getDots());
// you get the idea ...
}
printype::~printype()
{
// Have anything you need to do before destroying the object.
}
void printype::init()
{
this->setUnknwon(0);
this->setyear(0);
this->setMonth(1);
char dots[8][15] = {'\0'};
this->setDots(dots);
// you get the idea, you want to initialize all your variables since, for the most part they initially hold garbage.
}
void printype::setUnknown(int unknown)
{
if (unknown >= 0 && unknown < 127)
this->unknown15 = unknown;
else
error("Expecting unknown to be between 0 and 127"); // error should probably print the error and/or exit(-1) up to u
}
int printype::setYear(int year)
{
if (year >= 1 && year <= 99)
this->year8 = year;
else
error("Expecting year between 0 and 99"); // you may want to implement an error function!
}
int printype::getYear()
{
return this->year8;
}
void printype::setDots(char dots[8][15])
{
// you may want to do some verifications
memcpy(this->dots, dots, sizeof(dots));
}
void printype::setDots(char **dots) // this is a bit unsafe, use at your own risk.
{
if (dots)
{
unsigned int index = 0;
for (index = 0; index < 8; index++)
if (dots[index])
memcpy(this->dots[index], dots[index], 15);
else
error("dots required pointer ...");
}
else
error("dots required pointer ...");
}
char **getDots() // We will be returning a copy, we don't want the internal state to be affected, from outside, by using reference or pointers.
{
char **dots = new char*[8];
unsigned int index = 0;
for (index = 0; index < 8; index++)
{
dots[index] = new char[15];
memcpy(dots[index], this->dots[index], 15);
}
return dots;
}
// and well you get the idea ...
to use your class
printype *print_type_p = new print_type();
// or
printype pront_type_p();
// use the different public method to update the internal state.
print_type_p->setYear(3);
// or
print_type.setYear(3);
print_type_p->getYear();
// and so on.