且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

错误C4996:'ctime':此函数或变量可能不安全

更新时间:2021-10-17 23:36:21

请查看 ctime 的说明,您将注意到:

If you look at the description of ctime you will note:


此函数返回指向静态数据的指针,并且不是线程安全的。此外,它修改可能与gmtime和localtime共享的 static tm对象。 POSIX将此函数标记为过时,并建议使用strftime。

This function returns a pointer to static data and is not thread-safe. In addition, it modifies the static tm object which may be shared with gmtime and localtime. POSIX marks this function obsolete and recommends strftime instead.

对于导致字符串长于25的time_t值,行为可能未定义字符(例如年10000)

The behavior may be undefined for the values of time_t that result in the string longer than 25 characters (e.g. year 10000)

...这是很多需要担心的事情。

... that's a lot of things to worry about.

另一方面,如果您查看 strftime

On the other hand, if you look at strftime:


size_t strftime(char * str,size_t count,const char * format,tm * time);

size_t strftime( char* str, size_t count, const char* format, tm* time );

返回值

写入str指向的字符数组的字节数不包括终止'\ 0'成功。如果在可以存储整个字符串之前达到count,则返回0并且内容未定义。

number of bytes written into the character array pointed to by str not including the terminating '\0' on success. If count was reached before the entire string could be stored, ​0​ is returned and the contents are undefined.

所有参数都是显式的,因此您可以完全控制可能的数据竞争,并且没有溢出提供的缓冲区的风险

All the parameters are explicit, so that you fully control the possible data races, and there is no risk of overflowing the buffer provided as well.

这是C-way,C ++引入了< chrono> 函数 std :: put_time 也可以用于向流输出时间:

This is the C-way though, and C++ introduces the <chrono> in which a specific function std::put_time can also be used to output time to a stream:

#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>

int main() {
    std::time_t const now_c = std::time();
    std::cout << "One day ago, the time was "
              << std::put_time(std::localtime(&now_c), "%F %T") << '\n';
}

这是更好的,因为你不再需要担心可能的缓冲区溢出。

which is even better since you no longer have to worry about the possible buffer overflow.