开发者

warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’

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开发者_StackOverflow社区;
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?


  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.


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 :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜