0

I wrote a program which has to check if compiler meets POSIX requirements (so my time_t variable will hold proper dates), find today's year and generate bunch of random dates. Dates must be in a range of two years, last one and current (approximately).

Unfortunately the block which determines current year causes some sort of undefined behavior. Here's my code:

#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. I need time_t and tm structure variables (today, tm_today) used for determining today's year to be dynamic.

AKX
  • 152,115
  • 15
  • 115
  • 172
Mr. White
  • 51
  • 5

1 Answers1

3

gmtime() returns a pointer to an internal value (or a null pointer), which you must not pass to free(). And we lose the pointer to the memory we allocated.

struct tm *const tm_today = gmtime(today);
if (tm_today) {
    // use it
}
// DO NOT free(tm_today) - it's not ours
Toby Speight
  • 27,591
  • 48
  • 66
  • 103