getcwd() function expects the caller to supply a buffer big enough to hold the path of the current working directory plus a terminating
\0. How do you know how big the buffer needs to be? You don't.
Various man pages suggest using a buffer size of
MAXPATHLEN+1, or similar. Alas, neither constant is available on all systems.
Some systems allow you to pass
NULL, which makes
getcwd() allocate enough memory automatically. Alas, not all systems support this usage.
The most portable and convenient way to use
getcwd(), then, is to wrap it in a loop, calling with ever larger buffers until the path fits.
pgetcwd.c is such a wrapper. This returns a
malloc'ed string containing the current working directory. It is up to the caller to free this string when it is finished. If
errno contains details. Will write proper man page later.