我在C中声明指针的顺序真的很重要吗?getcwd()问题

chu*_*son 4 c unix getcwd

在Solaris 5.8计算机上,我有以下代码:

[非工作代码]

char *buf;
char *dir;
size_t psize;

psize = (size_t) 1024;
dir = getcwd(buf, psize);
Run Code Online (Sandbox Code Playgroud)

在此UNIX机器,上面并没有工作,试图运行该程序时,我得到一个分段错误.它只有在我dir 之前 声明时才有效buf:

[工作代码]

char *dir;
char *buf;
...
dir = getcwd(buf, psize);
Run Code Online (Sandbox Code Playgroud)

当使用另一种Unix版本时,例如Mac OS X,我没有得到任何关于如何编写代码的非常严格的规则.任何人都可以用上面的例子来解释发生了什么吗?谢谢!

Nik*_*sov 6

这是来自getcwd(3):

DESCRIPTION
     The getcwd() function copies the absolute pathname of the current working
     directory into the memory referenced by buf and returns a pointer to buf.
     The size argument is the size, in bytes, of the array referenced by buf.

     If buf is NULL, space is allocated as necessary to store the pathname.
     This space may later be free(3)'d.

那就是-设置bufNULLfree(3)dir完成时; 或者buf自己分配空间(因为你告诉getcwd(3)你有1K).

编辑:

所以为了清理一下,它要么:

char *dir = getcwd( NULL, 0 );

if ( dir == NULL ) { /* handle error */ }
/* use dir */
free( dir );
Run Code Online (Sandbox Code Playgroud)

要么

char buf[1024]; /* or allocate it with malloc(3) */

if ( getcwd( buf, 1024 ) == NULL ) { /* handle error */ }

/* use buf, DO NOT free it if it's on the stack or static, 
   only if malloc-ed */
Run Code Online (Sandbox Code Playgroud)