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*, because there simply seems to be no cross-platform way.
const string getcwd()
{
char* a_cwd = getcwd(NULL,0);
string s_cwd(a_cwd);
free(a_cwd);
return s_cwd;
}
UPDATE2: without Boost or Qt, the most common stuff can get long-winded (see accepted answer)
If you want to remain standard,
getcwdisn’t required to do anything if you pass to it a NULL; you should instead allocate on the stack a buffer that is “large enough” for most occasions (say, 255 characters), but be prepared for the occasion in whichgetcwdmay fail witherrno==ERANGE; in that case you should allocate dinamically a bigger buffer, and increase its size if necessary.Something like this could work (notice: not tested, just written by scratch, can be surely improved):
By the way, in your code there’s a very wrong thing: you are trying to dellocate a_cwd (which presumably, in the nonstandard extension, is allocated with malloc or with some other memory allocation function, since getcwd is thought for C) with
delete: you absolutely shouldn’t do that, keep in mind that each allocation method has its deallocation counterpart, and they must not be mismatched.