【发布时间】:2013-12-27 07:39:32
【问题描述】:
以下 C 程序尝试获取并打印当前 RHEL 主机的主机名。它会在这台机器上抛出一个segmentation fault。根据gethostname 的定义,我应该能够传递一个字符指针,不是吗?
当我改用 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 >
【问题讨论】: