今天在调试程序遇到一个段错误。而检查程序逻辑没有可能产生错误可能性。最终通过google找到了该问题的愿意。

以下是转来的:

发现出错在 inet_ntoa 那一行。查看了 inet_ntoa 的帮助,没有发现什么特别的地方。

试着打开编译的warning开关看看有没有什么发现:
 
  • [shengkui@uranus ~]$ gcc -g -o getaddr getaddr.c -Wall
  • getaddr.c: In function 'get_host_ip':
  • getaddr.c:26: warning: implicit declaration of function 'inet_ntoa'
  • getaddr.c:26: warning: format '%s' expects type 'char *', but argument 2 has type 'int'
  • inet_ntoa 没有声明,是因为没有加必须的头文件。
    inet_ntoa 的返回值是 “char *”, 而编译器似乎把它的返回值当成了int?是这个导致的错误吗?
    在64位的Linux 下,int是32位的,而指针(在这里是 char *)是64位的。问题应该就是出在这里!
     
    我把 inet_ntoa 需要的头文件加上去:
  • #include <sys/socket.h>
  • #include <netinet/in.h>
  • #include <arpa/inet.h>
  • 编译,运行,结果正确,没有段错误!
     
    这个问题提醒我们,函数的声明不是可有可无的,不要小看任何一个warning。

    相关文章: