0

I have a project about static source code analysis. The error message: "error C4996: 'ctime': This function or variable may be unsafe". 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.

 virtual bool onTLSConnect( const CertInfo& info )
    {
      printf( "status: %d\nissuer: %s\npeer: %s\nprotocol: %s\nmac: %s\ncipher: %s\ncompression: %s\n"
              "from: %s\nto: %s\n",
              info.status, info.issuer.c_str(), info.server.c_str(),
              info.protocol.c_str(), info.mac.c_str(), info.cipher.c_str(),
              info.compression.c_str(), ctime( (const time_t*)&info.date_from ),
              ctime( (const time_t*)&info.date_to ) );
      return true;
    }
lilya
  • 21
  • 1
  • 4

1 Answers1

0

The compiler message comes from using ctime at all, but your use will give incorrect results: Both calls to ctime will return the same address to an internal, static, thread-local buffer, meaning your call to printf will incorrectly display identical dates.

At the minimum, you should do this:

virtual bool onTLSConnect( const CertInfo& info )
{
    std::string dateFrom(ctime(reinterpret_cast< const time_t* >(&info.date_from));
    std::string dateTo  (ctime(reinterpret_cast< const time_t* >(&info.date_to));

    printf( "status: %d\nissuer: %s\npeer: %s\nprotocol: %s\nmac: %s\ncipher: %s\ncompression: %s\n"
          "from: %s\nto: %s\n",
          info.status, info.issuer.c_str(), info.server.c_str(),
          info.protocol.c_str(), info.mac.c_str(), info.cipher.c_str(),
          info.compression.c_str(), dateFrom.c_str(),
          dateTo.c_str() );
  return true;
}

On the subject of the compiler, you could disable this altogether with a #define, or you could disable it just when you need it:

virtual bool onTLSConnect( const CertInfo& info )
{
    #pragma warning(push)
    #pragma warning(disable:4996)
    std::string dateFrom(ctime(reinterpret_cast< const time_t* >(&info.date_from));
    std::string dateTo  (ctime(reinterpret_cast< const time_t* >(&info.date_to));
    #pragma warning(pop)

    printf( "status: %d\nissuer: %s\npeer: %s\nprotocol: %s\nmac: %s\ncipher: %s\ncompression: %s\n"
          "from: %s\nto: %s\n",
          info.status, info.issuer.c_str(), info.server.c_str(),
          info.protocol.c_str(), info.mac.c_str(), info.cipher.c_str(),
          info.compression.c_str(), dateFrom.c_str(),
          dateTo.c_str() );
  return true;
}
Medinoc
  • 6,577
  • 20
  • 42
  • Error: error C2065: 'date_to': undeclared identifier error C2228: left of '. c_str' must have class / struct / union – lilya Jun 27 '13 at 14:00