inet_ntoa函数段错误(Segmentation fault)
今天在用udp编写程序是,出现奇怪的问题:
inet_ntoa函数在调用时出现段错误,这个函数我再两个文件中都有使用,在一个文件中正常工作,在另一个文件中就出现段错误,百思不得其解,由于项目工期紧,所以有点心烦意乱。
后来喝点茶,仔细看了编译的输出,一个不起眼的警告提醒了我:
gcc -I../include -c -Wall -g -dH -fPIC -D_GNU_SOURCE testudp.c -o testudp.o
testudp.c: In function ‘main’:
testudp.c:17:27: warning: unused variable ‘sockClient’ [-Wunused-variable]
udp_sock_t *sockSrv, *sockClient;
^
testudp.c: In function ‘cb_msg_process’:
testudp.c:37:5: warning: implicit declaration of function ‘inet_ntoa’ [-Wimplicit-function-declaration]
msg_log_info("RECV(%s:%d):%s", inet_ntoa(clientaddr->sin_addr), ntohs(clientaddr->sin_port), pdata);
^
问题就在: * warning: implicit declaration of function ‘inet_ntoa’*
只要在该文件中包含对于的头文件即可:
#include <arpa/inet.h>
这就回到了一个好的编程习惯的问题了,由于项目紧,也许会忘记一些以前经常用的方法。
(1)编译代码是增加 -Wall 编译选项
(2)代码中出现的告警,请不要忽略,有可能就是函数名没有声明或变量类型错误等,有些告警其实就是错误