llvm / llvm/llvm-project

[flang] getcwd() terminates string with c_null_char instead of blank padding

Open
#223,778 0 comments 0 reactions 0 assignees View on GitHub
flang
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:

Image

Contributor guide

Open the contributing 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.