我正在使用 _getcwd 获取当前工作目录。该函数需要一个指向缓冲区的指针以及缓冲区大小。
在我的代码中我使用:
char *cwdBuf;
cwdBuf = malloc(100);
我不知道所需缓冲区的大小,因此我将内存保留得比所需的大。我想做的是使用正确的内存量。
有什么办法可以做到这一点吗?
最佳答案
您的目标平台是什么? getcwd()
documentation here提出了两个要点:
As an extension to the POSIX.1-2001 standard, Linux (libc4, libc5, glibc) getcwd() allocates the buffer dynamically using malloc() if buf is NULL on call. In this case, the allocated buffer has the length size unless size is zero, when buf is allocated as big as necessary. It is possible (and, indeed, advisable) to free() the buffers if they have been obtained this way...
...The buf argument should be a pointer to an array at least PATH_MAX bytes long. getwd() does only return the first PATH_MAX bytes of the actual pathname.
关于调用 malloc,未知大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5257479/