生成具有固定范围的随机日期

Generating random dates with a fixed range

我写了一个程序,它必须检查编译器是否满足 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_ttm 结构变量(todaytm_today)用于确定今天的年份是动态的。

gmtime() returns 指向内部值(或空指针)的指针,您不得将其传递给 free()。我们丢失了指向我们分配的内存的指针。

struct tm *const tm_today = gmtime(today);
if (tm_today) {
    // use it
}
// DO NOT free(tm_today) - it's not ours