开发者

Call to malloc, unknown size

开发者 https://www.devze.com 2023-02-16 11:57 出处:网络
I am getting the current working directory with _getcwd. The function requires a pointer to t开发者_运维知识库he buffer, and the buffers size.

I am getting the current working directory with _getcwd. The function requires a pointer to t开发者_运维知识库he buffer, and the buffers size.

In my code I am using:

char *cwdBuf;
cwdBuf = malloc(100);

I don't know the size of the buffer needed, so I am reserving memory way to big than is needed. What I would like to do is use the correct amount of memory.

Is there any way to do this?


What is your target platform? The getcwd() documentation here makes two important points:

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.


There is usually a MAX_PATH macro defined which you can use. Also is there any reason not to just allocate on the stack?

Edit:

From the MSDN Docs:

#include <direct.h>
#include <stdlib.h>
#include <stdio.h>

int main( void )
{
   char* buffer;

   // Get the current working directory: 
   if( (buffer = _getcwd( NULL, 0 )) == NULL )
      perror( "_getcwd error" );
   else
   {
      printf( "%s \nLength: %d\n", buffer, strnlen(buffer) );
      free(buffer);
   }
}

So it looks like if you pass in NULL, it allocates a buffer for you.


The size of the current working directory is unknown as such but its upper limit can be asked for.

The correct way of allocating memory to use for getcwd() is by querying the system for the maximum length buffer required, via pathconf(".", _PC_PATH_MAX); before allocating the buffer and calling getcwd().

The OpenGroup UNIX standard manpages document this for getcwd() in the example code given. Quote:

#include <stdlib.h>
#include <unistd.h>
...
long size;
char *buf;
char *ptr;

size = pathconf(".", _PC_PATH_MAX);

if ((buf = (char *)malloc((size_t)size)) != NULL)
    ptr = getcwd(buf, (size_t)size);
...


How about realloc() once you know the size of the result?

0

精彩评论

暂无评论...
验证码 换一张
取 消