If realpath() allocated memory for result and failed, the memory is freed in each place where return is performed. More, the function needs to track the allocation status, to not free user-supplied buffer.
Consolidate the memory handling in the wrapper, freeing the buffer if the actual worker failed.
This conflicts with the patch in PR 219154, I will pass the PR change first.