I'm trying to get current local time in C++ with the following code:
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
Unfortunately, I'm getting "debug assertion failed" when calling localtime (somewhere in __getgmtimebuf -> _malloc_crt) with the message _BLOCK_TYPE_IS_VALID(pHead->nBlockUse).
Am I missing something, do I need some compile flag (I'm using vs 2012 with c++11)?
If not, what alternative do I have?
I cannot post the entire code and it's not easy to isolate more of the context.
It seems that the error is not from the time functions but from the rest of the logic (as they work in a separate project) and I will try to find what's causing it but still, I feel that the error is kinda obscure.
What I was doing was something like this:
#include <iostream>
#include <chrono>
#include <ctime>
#include <string>
#include <thread>
class A
{
public:
void time()
{
//time_t rawtime;
//struct tm * timeinfo;
//time (&rawtime);
//timeinfo = localtime (&rawtime);
time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << std::ctime(&now);
}
};
class B
{
public:
void run(A *a)
{
this->a = a;
this->t = new std::thread(t_f, *this);
this->t->join();
}
~B()
{
delete t;
delete a;
}
friend void t_f(B &b);
private:
A *a;
std::thread *t;
};
void t_f(B &b)
{
b.a->time();
}
int main()
{
B b;
b.run(new A());
return 0;
}
What I didn't know is that the destructor of B was called before the join and before the thread finished its job.
SOLUTION:
- the time functions (whether from ctime or chrono) work as expected
- pass B to t_f() by pointer or std::ref
Both suspicions from Keith Thompson and Mats Petersson were grounded and correct so I will mark Keith's answer correct as it was the first good lead to solve this obscure error even though I didn't present enough informations initially.
Thank you