Warning: format '% s expects type' char *, but argument 2 is of type 'int

I think this code and error are 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 executable 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 a format warning and can this cause a segmentation error?

+3
source share
2 answers
  • Please compile your code with -Wall.
  • include header file for inet_ntop (arpa / inet.h)
  • read the inet_ntop (3) man page and be careful with the parameters.
+11
source

, :

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

, inet_ntop char*. , -, <arpa/inet.h> - , int.

, , () , . - : -)

+5

Source: https://habr.com/ru/post/1745982/


All Articles