奇怪的段错误

weird Seg fault

出于某种原因,我的代码引发了段错误。我认为这与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);