tags:

views:

325

answers:

2

I think this code and error is self-explanatory, but I don't know why?

Environment:
OS: Mac OS X 10.6.1
Compiler: i686-apple-darwin10-gcc-4.2.1

code:

 1  #include <stdio.h>
 2  #include <stdlib.h>
 3  #include <netdb.h>
 4  #include <sys/socket.h>
 5  
 6  int 
 7  main(int argc, char **argv)
 8  {
 9      char           *ptr, **pptr;
10      struct hostent *hptr;
11      char            str[32];
12  
13      //ptr = argv[1];
14      ptr = "www.google.com";
15  
16      if ((hptr = gethostbyname(ptr)) == NULL) {
17          printf("gethostbyname error for host:%s\n", ptr);
18  
19      }
20      printf("official hostname:%s\n", hptr->h_name);
21  
22      for (pptr = hptr->h_aliases; *pptr != NULL; pptr++)
23          printf(" alias:%s\n", *pptr);
24  
25      switch (hptr->h_addrtype) {
26      case AF_INET:
27      case AF_INET6:
28          pptr = hptr->h_addr_list;
29  
30          for (; *pptr != NULL; pptr++)
31              printf(" address:%s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
32          break;
33      default:
34          printf("unknown address type\n");
35          break;
36      }
37      return 0;
38  }


compiler and executed output below:

zhumatoMacBook:CProjects zhu$ gcc gethostbynamedemo.c 
gethostbynamedemo.c: In function ‘main’:
gethostbynamedemo.c:31: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
zhumatoMacBook:CProjects zhu$ ./a.out 
official hostname:www.l.google.com
 alias:www.google.com
Segmentation fault

Why am I getting the format warning and could this be the cause of the segmentation fault?

+9  A: 

Hey,

  1. Please compile your code using -Wall.
  2. include header file for inet_ntop (arpa/inet.h)
  3. read inet_ntop(3) man page and be careful about parameter types.
Daniel Băluţă
+1 very quick answer.
Jack
It work. Thank you very much.
py_zhu
+5  A: 

If I count right, the warning is emitted for this line:

printf(" address:%s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));

According to this page, inet_ntop does indeed return char*. However, apparently you don't include <arpa/inet.h> - this can cause this warning, as the compiler may default to interpret an undeclared function as one returning an int.

Next time, please mark the problematic code line(s) with e.g. a comment - it would increase your chances of getting useful answers :-)

Péter Török
"the compiler may default to interpret an undeclared function as one returning an int."You are right, this is the point.And thanks for your advice.
py_zhu