-
Notifications
You must be signed in to change notification settings - Fork 52
Description
I have tested the strptime example code:
use datetime_module
type(datetime) :: date1,date2
type(timedelta) :: timediff
! Example times in "YYYYMMDD hhmmss" format
character(len=15) :: str1 = "20130512 091519"
character(len=15) :: str2 = "20131116 120418"
date1 = strptime(str1,"%Y%m%d %H%M%S")
date2 = strptime(str2,"%Y%m%d %H%M%S")
timediff = date2-date1
print *, timediff
print *, timediff%total_seconds()
My test environment is MacOS, and the compiler is gfortran version: 14.2.0.
The above code can be compiled and run, but it always reports "Program received signal SIGSEGV: Segmentation fault - invalid memory reference."
This is likely due to mismatched string handling — especially around how Fortran interoperates with C in the strptime wrapper. If the strings passed in (str1, format) are declared as character(len=*), Fortran passes them with hidden length arguments, and this can cause issues in interoperability unless handled explicitly.
If c_strptime is written in C or Fortran using ISO_C_BINDING, you must make sure it's correctly defined for character strings. If you’re using character(len=*) without proper binding or copying into C-style null-terminated buffers, you must explicitly convert the strings.
Here is how I fixed this problem, by modifying the code in "type(datetime) function strptime(str,format)" of datetime_module.f90:
type(datetime) function strptime(str,format)
! A wrapper function around C/C++ strptime function.
! Returns a `datetime` instance.
character(*), intent(in) :: str, format
integer :: rc
type(tm_struct) :: tm
character(len=256) :: str_buf, fmt_buf
! fixed by guoding chen
str_buf = trim(str)
fmt_buf = trim(format)
rc = c_strptime(trim(str_buf) // c_null_char, trim(fmt_buf) // c_null_char, tm)
strptime = tm2date(tm)
end function strptime
For me this completely fixed the problem. AND, it could also be a problem with my system/compiler? I hope this isn't a common problem.