本文介绍了错误C4996:'ctime':此函数或变量可能不安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于静态源代码分析的大项目,一切都编译成功,除了一件事。我在标题中提供了错误消息。让我困惑的一点是,它给出一个错误消息说不安全。我认为应该只是警告,而不是错误。顺便说一下,我使用Visual Studio 2012.这里是代码的部分,我得到的错误,在Ctime。如果有人可以帮助我克服这个错误,我会很高兴。

I have a large project about static source code analysis, and everything compiles successfully, except for one thing. I have provided the error message in the title. The point that confuses me is that it gives an error message saying unsafe. I thought it should be just warning, not an error. By the way, I'm using Visual Studio 2012. Here is the part of the code where I get the error, in ctime. If someone can help me overcome this error, I would be glad.

void CppCheckExecutor::reportProgress(const std::string &filename, const char stage[], const std::size_t value)
{
     (void)filename;

     if (!time1)
         return;

     // Report progress messages every 10 seconds
     const std::time_t time2 = std::time(NULL);
     if (time2 >= (time1 + 10)) {
         time1 = time2;

         // current time in the format "Www Mmm dd hh:mm:ss yyyy"
         const std::string str(std::ctime(&time2));

         // format a progress message
         std::ostringstream ostr;
         ostr << "progress: "
              << stage
              << ' ' << value << '%';
         if (_settings->_verbose)
             ostr << " time=" << str.substr(11, 8);

         // Report progress message
         reportOut(ostr.str());
     }
}


推荐答案

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

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

对于导致字符串长于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.

另一方面,如果您查看:

On the other hand, if you look at strftime:

返回值

写入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.

这篇关于错误C4996:'ctime':此函数或变量可能不安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 06:25