Search code examples
c++timec++-chrono

How to get the current time in c++ in a " Safe " way


I'm not new to C++, but I mostly only use the most basic standard library features like <iostream>, <vector>, <map>, etc.

Right now, I'm working on a simple game and I'm working on a logger class, but I'm stuck on getting the current time.

Don't get me wrong, I've seen a lot of ways to get the time in StackOverflow and Google, but none of them are "safe" according to Visual Studio. When I use, for example, asctime() or ctime(), I get this error:

['ctime': This function or variable may be unsafe. Consider using ctime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details].

But when I try to do it the good way and use safe versions, I find them even more complicated, for example this is the ctime() function:

ctime(const time_t *const_time)

compared to ctime_s():

ctime_s(char *const _Buffer, const size_t _SizeinBytes,const time_t *const _Time)

Again looking on the Internet didn't help me, so here I am, asking you guys about how to get the current time, and by time I mean something like 10:20 or something similar, using "safe" methods.


Solution

  • The asctime() and ctime() functions are "unsafe" because they return a pointer to static buffers that may or may not be thread-safe depending on implementation, and if they are not thread-safe then they could be overwritten by other threads before you have a chance to use them.

    The "more secure" asctime_s() and ctime_s() functions write to pre-allocated buffers that you must provide, eg:

    time_t now = time(NULL);
    //char *str = asctime(localtime(&now));
    tm now_tm = {};
    char str[26] = {};
    localtime_s(&now_tm, &now);
    asctime_s(str, 26, &now_tm);
    // use str as needed...
    
    time_t now = time(NULL);
    //char *str = ctime(&now);
    char str[26] = {};
    ctime_s(str, 26, &now);
    // use str as needed...