Skip to content

Commit

Permalink
Fix undefined behaviour in get_string
Browse files Browse the repository at this point in the history
`c_f_pointer` does not assign a length to the ponted-to character string
 `f_ptr`, so that debug builds (with bounds checks) cause a "substring
 out of bounds" error when accessing `f_ptr` to assign it to `f_string`.

 `f_ptr` is now an array and `c_f_pointer` gets passed the shape that
 should be assigned. The array is then read into the `f_string` string
 in a do-loop.
  • Loading branch information
GPMueller committed Aug 16, 2021
1 parent ba6cab7 commit 4598ef3
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions fortran/ovf.f90
Expand Up @@ -101,8 +101,9 @@ function get_string(c_pointer) result(f_string)
type(c_ptr), intent(in) :: c_pointer
character(len=:), allocatable :: f_string

integer(c_size_t) :: l_str
character(len=:), pointer :: f_ptr
integer :: idx
integer(c_size_t) :: l_str
character(len=1), dimension(:), pointer :: f_ptr

interface
function c_strlen(str_ptr) bind ( C, name = "strlen" ) result(len)
Expand All @@ -113,9 +114,12 @@ end function c_strlen
end interface

l_str = c_strlen(c_pointer)
call c_f_pointer(c_pointer, f_ptr)
call c_f_pointer(c_pointer, f_ptr, [l_str])

f_string = f_ptr(1:l_str)
allocate(character(l_str) :: f_string)
do idx=1,l_str
f_string(idx:idx)=f_ptr(idx)
end do
end function get_string

! Assign from C string wrapper to Fortran string
Expand Down Expand Up @@ -170,7 +174,7 @@ function get_c_ovf_segment(segment) result(c_segment)
c_segment%valuedim = segment%ValueDim
c_segment%valueunits = segment%ValueUnits
c_segment%valuelabels = segment%ValueLabels

c_segment%meshtype = segment%MeshType
c_segment%meshunits = segment%MeshUnits
c_segment%pointcount = segment%PointCount
Expand Down

0 comments on commit 4598ef3

Please sign in to comment.