do not unconditionally use PATH_MAX with getcwd

Instead, grow a buffer until getcwd either succeeds or fails with an errno different than ERANGE
(meaning the passed buffer was too short to represent the actual path).
Reset errno before calling getcwd to check it eventually did not fail.