【问题标题】:When having a Segmentation Fault change the message error shown发生分段错误时,更改显示的消息错误
【发布时间】:2018-06-29 05:57:26
【问题描述】:

我有以下代码将日期转换为毫秒:

long lond dateToMs(const char* text)
{
     std::tm tm = {};
     const char* snext = ::strptime(text, "%d-%m-%Y %H:%M:%S", &tm);
     auto time_point = std::chrono::system_clock::from_time_t(std::mktime(&tm));
     return time_point.time_since_epoch() / std::chrono::milliseconds(1) + std::atof(snext) * 1000.0f;
}

如果我有一个不存在的日期 例如:40-10-2015 12:23:45.2354,程序会显示以下消息:Segmentation fault (core dumped) 相反,我想显示类似The introduced date it's not valid 的内容。 我尝试了一个 try..catch 块,如下所示:

long long dateToMs(const char* text)
{
 try{
  std::tm tm = {};
  const char* snext = ::strptime(text, "%d-%m-%Y %H:%M:%S", &tm); 
  auto time_point = std::chrono::system_clock::from_time_t(std::mktime(&tm)); 
  return time_point.time_since_epoch()/std::chrono::milliseconds(1)+std::atof(snext)*1000.0f;
 }
 catch(const std::exception &)
 {
    std::cout << "The introduced date it's not valid" << std::endl;
 };
}

但它显示相同的错误:Segmentation fault (core dumped),我必须做什么才能显示我想要的消息错误。

【问题讨论】:

    标签: c++ datetime error-handling segmentation-fault try-catch


    【解决方案1】:

    您没有考虑snext 为空的可能性。

    long long dateToMs(const char* text)
    {
         std::tm tm = {};
         const char* snext = ::strptime(text, "%d-%m-%Y %H:%M:%S", &tm);
         if ( snext )
         {
              auto time_point = std::chrono::system_clock::from_time_t(std::mktime(&tm));
              return time_point.time_since_epoch() / std::chrono::milliseconds(1) + std::atof(snext) * 1000.0f;
         }
         else
         {
              std::cout << "The introduced date it's not valid";
         }
    
    
    }
    

    Live sample

    【讨论】:

    • 我已经尝试过这段代码,并且出现了相同的Segmentation fault (core dumped) 错误。我已经看到,当您尝试与 snext 指针交互时,例如执行 std::cout
    • @david.t_92 我添加了一个链接来演示代码的工作原理。
    • 谢谢你,它有效,问题是我在编译时使用了一个标志
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 2014-11-30
    相关资源
    最近更新 更多