For some reason, my code is throwing a segfault. I think it has something to do with the actual use of the timeinfo variable, but I am not too sure. I have no idea why not using the variable would throw a seg fault, and using it will not throw a seg fault.
this code will throw a seg fault: 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;
}
this code will not: 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;
}
here is another weird case: https://onlinegdb.com/rkOTCZKs4
struct tm * timeinfo;
strptime(char_array, "%Y-%m-%dT%H:%M:%S", timeinfo);
timeinfo
is a pointer, but it's uninitialized, resulting in undefined behavior. You're lucky it didn't wipe your hard drive. Instead, it probably just wrote the date to random bytes in memory. If that memory happens to be real memory for your app, you'll just get weird bugs. If that memory happens to not be memory your app has, the operating system will probably crash your app.
The correct way of doing this would be:
struct tm timeinfo;
memset(&timeinfo, 0, sizeof(struct tm));
strptime(char_array, "%Y-%m-%dT%H:%M:%S", &timeinfo);