gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:11:46 27 4
gpt4 key购买 nike

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

[非工作代码]

char *buf;
char *dir;
size_t psize;

psize = (size_t) 1024;
dir = getcwd(buf, psize);

在这台 unix 机器上,上面的代码 工作,我在尝试运行该程序时遇到段错误。它只有在我声明 dir before buf 时才有效:

[工作代码]

char *dir;
char *buf;
...
dir = getcwd(buf, psize);

当使用另一种 Unix 版本(例如 Mac OS X)时,我没有得到任何关于如何编写代码的似乎非常严格的规则。任何人都可以解释上面的例子是怎么回事吗?谢谢!

最佳答案

这里来自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.

That is - set the buf to NULL and free(3) the dir when done; OR allocate space for the buf yourself (since you are telling the getcwd(3) you have 1K there).

Edit:

So to clean it up a bit, it's either:

char *dir = getcwd( NULL, 0 );

if ( dir == NULL ) { /* handle error */ }
/* use dir */
free( dir );

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 */

关于c - 我声明指针的顺序在 C 中真的很重要吗? getcwd() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2619319/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com