以下 C 程序尝试获取并打印当前 RHEL 主机的主机名。segmentation fault
它在这台机器上抛出一个。根据gethostname的定义,我应该能够传递一个 char 指针,不是吗?
当我改用 char 数组(如char hname[255]
)时,调用gethostname
有效。(如果我这样做了,我将如何将数组返回到 main?)
#include <stdio.h>
#include <unistd.h>
char * fetchHostname()
{
// using "char hname[255]" gets me around the issue;
// however, I dont understand why I'm unable to use
// a char pointer.
char *hname;
gethostname(hname, 255 );
return hname;
}
int main()
{
char *hostname = fetchHostname();
return 0;
}
输出:
pmn@rhel /tmp/temp > gcc -g test.c -o test
pmn@rhel /tmp/temp >
pmn@rhel /tmp/temp > ./test
Segmentation fault
pmn@rhel /tmp/temp >