wavebitscientific / datetime-fortran

Date and time manipulation for modern Fortran
MIT License
137 stars 51 forks source link

strptime does not zero tm struct before calling c_strptime #49

Closed nichannah closed 4 years ago

nichannah commented 6 years ago

man strptime gives an example code like the below:

   int
       main(void)
       {
           struct tm tm;
           char buf[255];

           memset(&tm, 0, sizeof(struct tm));
           strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm);
           strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm);
           puts(buf);
           exit(EXIT_SUCCESS);
       }

The tm struct is zeroed before calling. datetime-fortran strptime does not do this which means that depending on the time string/format parts of the tm struct can be left containing uninitialised values.

milancurcic commented 6 years ago

Good catch! Did you encounter any case where this caused unexpected behavior?

Would something like this work?

type,bind(c) :: tm_struct

  !! A derived type provided for compatibility with C/C++ time struct.
  !! Allows for calling strftime and strptime procedures through the 
  !! iso_c_binding.

  integer(kind=c_int) :: tm_sec = 0  !! Seconds      [0-60] (1 leap second)
  integer(kind=c_int) :: tm_min = 0  !! Minutes      [0-59]
  integer(kind=c_int) :: tm_hour = 0 !! Hours        [0-23]
  integer(kind=c_int) :: tm_mday = 0 !! Day          [1-31]
  integer(kind=c_int) :: tm_mon = 0  !! Month        [0-11]
  integer(kind=c_int) :: tm_year = 0 !! Year - 1900
  integer(kind=c_int) :: tm_wday = 0 !! Day of week  [0-6]
  integer(kind=c_int) :: tm_yday = 0 !! Days in year [0-365]
  integer(kind=c_int) :: tm_isdst= 0 !! DST          [-1/0/1]

endtype tm_struct