【问题标题】:non-standard / non-POSIX getcwd() not calling malloc非标准/非 POSIX getcwd() 不调用 malloc
【发布时间】:2014-10-10 08:41:46
【问题描述】:

我误解了 getcwd 手册页中这句话的哪一部分?

   char *getcwd(char *buf, size_t size);
   ...
   As  an  extension  to  the  POSIX.1-2001 standard, Linux (libc4, libc5,
   glibc) getcwd() allocates the buffer dynamically using malloc(3) if buf
   is NULL.  In this case, the allocated buffer has the length size unless
   size is zero, when buf is allocated as big as  necessary.   The  caller
   should free(3) the returned buffer.

因为

 21         char * buffer = NULL;
 22         size_t bufferSize = 0;
 23         getcwd(buffer, bufferSize);
 24         printf("%s\n", buffer);

在第 24 行导致 Seg-Fault 并且 gdb 的回溯告诉我缓冲区 = 0x0?

编辑:

 getcwd(buffer, bufferSize);

无论出于何种原因仍然无法正常工作,但是

 buffer = getcwd(NULL, 0);

【问题讨论】:

    标签: posix getcwd


    【解决方案1】:

    您错过了 C 仅按值调用;不通过引用调用:

    getcwd(buffer, bufferSize);
    

    可以改变指针buffer(只有buffer指向的东西,但因为它是NULL...)。这就是为什么你需要使用getcwd(这个非标准版本)返回的值返回

    您还错过了阅读该手册页的 RETURN VALUE 部分,或者误解了引用部分的内容 调用者应该释放(3) 返回的缓冲区。: -)

    【讨论】:

    • AAAAAAAAAAAAAAAAAAAHHHHHHHHHHHHHHHHH,是的,你是对的,这就是为什么 getline 和 getdelim 使用 char **buffer...
    • @Kdawg 没错。如果您认为此答案有帮助,下一步是单击向上箭头和/或下面的复选标记以“接受”答案。
    • 对不起,“投票需要 15 声望”... 有一天我会到达那里
    【解决方案2】:

    应该是:

     printf("%s\n", buffer);
    

    因为%s 采用char*,而不是char

    如果你有警告,你就会知道这一点。

    【讨论】:

    • 我有它作为 printf("%s\n", buffer);现在但没有任何改变并且 errno = 0?
    • 这忽略了问题。 buffer 只能是NULL
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    相关资源
    最近更新 更多