我编写了一个程序,该程序必须检查编译器是否满足POSIX要求(因此我的time_t
变量将保留正确的日期),查找今天的年份并生成一堆随机日期。日期的范围必须为两年,最后一个并且是当前日期(大约)。
不幸的是,确定当年的区块导致某种不确定的行为。这是我的代码:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define N 5
#define ONE_YEAR 31536000
#define TWO_YEARS 63072000
#define TM_AND_POSIX_YEAR_DIFF 70
int main(void) {
// Start of the block which causes undefined behavior
struct tm *tm_today = (struct tm *)malloc(sizeof(struct tm));
short td_year;
time_t *today = (time_t *)malloc(sizeof(time_t));
time_t t[N];
// Checking if compiler meets POSIX requirements
time_t check = 86400;
if (strcmp(asctime(gmtime(&check)), "Fri Jan 02 00:00:00 1970\n") != 0)
return 1;
// Determining current year
*today = time(NULL);
tm_today = gmtime(today);
td_year = (*tm_today).tm_year - TM_AND_POSIX_YEAR_DIFF;
free(today);
free(tm_today);
// End of the block which causes undefined behavior
// Generating random dates
for (unsigned char i = 0; i < N; ++i) {
t[i] = (time_t)round(((double)rand() / RAND_MAX) * TWO_YEARS) +
ONE_YEAR * td_year;
printf("%d\n", t[i]);
puts(asctime(gmtime(&t[i])));
}
return 0;
}
P.S。我需要time_t
和tm
结构变量(today
,tm_today
)来确定今天的年份是动态的。
答案 0 :(得分:3)
gmtime()
返回一个指向内部值的指针(或空指针),您不得将其传递给free()
。而且我们丢失了指向分配的内存的指针。
struct tm *const tm_today = gmtime(today);
if (tm_today) {
// use it
}
// DO NOT free(tm_today) - it's not ours