Sorry to keep hammering on this, but I\'m trying to learn :). Is this any good? And yes, I care about memory leaks. I can\'t find a decent way of preallocating the char*, be
This will work on Windows and Linux, since they both support the automatic allocation behavior when the buf
argument to getcwd
is NULL. However, be aware that this behavior is not standard, so you may have issues on more esoteric platforms.
You can do it without relying on this behavior, though:
const string getcwd()
{
size_t buf_size = 1024;
char* buf = NULL;
char* r_buf;
do {
buf = static_cast<char*>(realloc(buf, buf_size));
r_buf = getcwd(buf, buf_size);
if (!r_buf) {
if (errno == ERANGE) {
buf_size *= 2;
} else {
free(buf);
throw std::runtime_error();
// Or some other error handling code
}
}
} while (!r_buf);
string str(buf);
free(buf);
return str;
}
The above code starts with a buffer size of 1024, and then, if getcwd
complains that the buffer is too small, it doubles the size and tries again, and repeats until it has a large enough buffer and succeeds.
Note that calling realloc
with its first argument as NULL is identical to malloc
.