调用 malloc,未知大小

标签 c

我正在使用 _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/

相关文章:

c - Printf big double value 在 C 中具有高精度

c - 如何使用 malloc() 在 redhat 中分配比 RAM 多的内存?

c - 在运行时从共享库导入结构 - 在编译时没有头文件

c - C 结构中的自动字段重新排序以避免填充

c - 如何发送数组作为函数参数?

谁能帮我找出为什么这个 C 程序可以在 VS2005 上运行但不能在 DEV-C++ 上运行

c++ - 如何检查 malloc() 实现中返回数据的对齐?

C编程: reading and writing binary files

c - 从命令行获取输入?

c - C 中的 fgets 不返回字符串的一部分