The following C program attempts to fetch and print the host name of the current RHEL host. It throws a segmentation fault
on this machine. As per the definition of gethostname I should be able to pass a char pointer, shouldn't I?
When I use a char array instead (like char hname[255]
), the call to gethostname
works. (If I did this how would I return the array to 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;
}
Output:
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 >
As
gethostname
man said:You need a place to store the function information, so declare hostname as an array, not a pointer.