[flang] getcwd() terminates string with c_null_char instead of blank padding
- Dominant language
- LLVM
- Stars
- 40.5k
- Forks
- 18.7k
- PR merge metrics
- PR metrics pending
Description
### Summary
The `getcwd()` implementation in flang (23.1.1 on mac obtained via homebrew) appears to use the c_null_char to end the string rather than padding the result with blanks as would be expected. This means that the trim() intrinsic does not work as expected on the result, and the string is full of junk.
I believe that the result from `getcwd()` should be padded with blanks rather than using the C string terminator.
### Example
Example below, including a workaround wrapper for trim which scans for the c_null_char to terminate.
```fortran
program getcwd_test
implicit none
character(len=256) :: my_cwd
call getcwd(my_cwd)
write(*,*) my_cwd // " hello"
write(*,*) trim(my_cwd) // " hello"
write(*,*) trim_workaround(my_cwd) // " hello"
contains
function trim_workaround(s) result(t)
use iso_c_binding, only: c_null_char
character(len=*), intent(in) :: s
character(len=:), allocatable :: t
integer :: n
n = index(s, c_null_char)
if (n > 0) then
t = trim(s(:n-1))
else
t = trim(s)
end if
end function trim_workaround
end program getcwd_test
```
Outputs the following:
Contributor guide
Research direction
Start at the flang implementation and entry point for getcwd(), using the provided Fortran reproducer to observe how the returned character value is terminated and padded. Confirm the fix by checking that trim(my_cwd) produces the expected path without junk and that the result uses blank padding rather than c_null_char.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- fortran
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 55/100