A better way would be to just rely on pathconf():
- if pathconf() returns an error, return an error as well
- Otherwise use the length pathconf() returned, but use a canary at the end of the buffer to check for buffer overflows.
The latter point is important because readdir_r in combination with pathconf is unsafe, see e.g. https://womble.decadent.org.uk/readdir_r-advisory.html