出于某种原因,我的代码引发了段错误。我认为这与timeinfo变量的实际使用有关,但我不太确定。我不知道为什么不使用该变量会引发段错误,而使用它不会引发段错误。
此代码将抛出段错误:https://www.onlinegdb.com/Hk1JT-Ys4
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <string.h>
using namespace std;
int main ()
{
string timeString = "3019-05-17T22:9:00Z";
char char_array[timeString.length() + 1];
strcpy(char_array, timeString.c_str());
struct tm * timeinfo;
strptime(char_array, "%Y-%m-%dT%H:%M:%S", timeinfo);
// time_t now = time(0);
// struct tm * gmtNow= gmtime(&now);
// if(mktime(timeinfo)>mktime(gmtNow))
// puts("yes");
// else
// puts("no");
char buffer [80];
strftime (buffer,80,"%Y-%m-%dT%H:%M:%S", timeinfo);
puts (buffer);
return 0;
}
这段代码不会: https://onlinegdb.com/H10GTZYoV
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <string.h>
using namespace std;
int main ()
{
string timeString = "3019-05-17T22:9:00Z";
char char_array[timeString.length() + 1];
strcpy(char_array, timeString.c_str());
struct tm * timeinfo;
strptime(char_array, "%Y-%m-%dT%H:%M:%S", timeinfo);
time_t now = time(0);
struct tm * gmtNow= gmtime(&now);
if(mktime(timeinfo)>mktime(gmtNow))
puts("yes");
else
puts("no");
char buffer [80];
strftime (buffer,80,"%Y-%m-%dT%H:%M:%S", timeinfo);
puts (buffer);
return 0;
}
还有一个奇怪的例子: https://onlinegdb.com/rkOTCZKs4
最佳答案
struct tm * timeinfo;
strptime(char_array, "%Y-%m-%dT%H:%M:%S", timeinfo);
timeinfo
是一个指针,但它未初始化,导致未定义的行为。你很幸运,它没有删除你的硬盘。相反,它可能只是将日期写入内存中的随机字节。如果该内存碰巧是您应用程序的真实内存,您只会遇到奇怪的错误。如果该内存碰巧不是您的应用程序的内存,操作系统可能会使您的应用程序崩溃。
正确的做法是:
struct tm timeinfo;
memset(&timeinfo, 0, sizeof(struct tm));
strptime(char_array, "%Y-%m-%dT%H:%M:%S", &timeinfo);
关于c++ - 奇怪的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55961930/