標準のままにしたい場合getcwd
は、NULL を渡しても何もする必要はありません。代わりに、ほとんどの場合に「十分な大きさ」のバッファ (たとえば 255 文字) をスタックに割り当てる必要がありますが、 でgetcwd
失敗する可能性がある場合に備えてくださいerrno==ERANGE
。その場合、より大きなバッファーを動的に割り当て、必要に応じてそのサイズを大きくする必要があります。
このようなものが機能する可能性があります(注意:テストされておらず、スクラッチで書かれただけで、確実に改善できます):
string getcwd()
{
const size_t chunkSize=255;
const int maxChunks=10240; // 2550 KiBs of current path are more than enough
char stackBuffer[chunkSize]; // Stack buffer for the "normal" case
if(getcwd(stackBuffer,sizeof(stackBuffer))!=NULL)
return stackBuffer;
if(errno!=ERANGE)
{
// It's not ERANGE, so we don't know how to handle it
throw std::runtime_error("Cannot determine the current path.");
// Of course you may choose a different error reporting method
}
// Ok, the stack buffer isn't long enough; fallback to heap allocation
for(int chunks=2; chunks<maxChunks ; chunks++)
{
// With boost use scoped_ptr; in C++0x, use unique_ptr
// If you want to be less C++ but more efficient you may want to use realloc
std::auto_ptr<char> cwd(new char[chunkSize*chunks]);
if(getcwd(cwd.get(),chunkSize*chunks)!=NULL)
return cwd.get();
if(errno!=ERANGE)
{
// It's not ERANGE, so we don't know how to handle it
throw std::runtime_error("Cannot determine the current path.");
// Of course you may choose a different error reporting method
}
}
throw std::runtime_error("Cannot determine the current path; the path is apparently unreasonably long");
}
ところで、あなたのコードには非常に間違ったことがあります: a_cwd の割り当てを解除しようとしています (これはおそらく、標準外の拡張機能では、malloc または他のメモリ割り当て関数で割り当てられます。getcwd は C で使用されると考えられているためdelete
です)。絶対にそうすべきではありません。各割り当て方法には対応する割り当て解除があり、それらが一致していてはならないことに注意してください。