以下 C 程序尝试获取并打印当前 RHEL 主机的主机名。它在这台机器上抛出一个段错误
。根据 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 >
最佳答案
正如 gethostname
人所说:
The gethostname() function shall return the standard host name for the current machine. The namelen argument shall specify the size of the array pointed to by the name argument. The returned name shall be null-terminated, except that if namelen is an insufficient length to hold the host name, then the returned name shall be truncated and it is unspecified whether the returned name is null-terminated.
您需要一个地方来存储函数信息,因此将主机名声明为数组,而不是指针。
#include <unistd.h>
char * fetchHostname(char *hostname, int size)
{
// using "char hname[255]" gets me around the issue;
// however, I dont understand why I'm unable to use
// a char pointer.
gethostname(hostname, size);
return hostname;
}
int main()
{
char hostname[HOST_NAME_MAX + 1];
fetchHostname(hostname, HOST_NAME_MAX);
return 0;
}
关于c - 无法将 char 指针传递给 gethostname (Linux),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20796823/