inet_ntoa之坑------再谈不可重入函数中的static

来源:互联网 发布:药品销售人员软件 编辑:程序博客网 时间:2024/06/05 22:36

      不想用过多的话语来啰嗦, 还是看代码吧(如下结果非常让人吃惊):

#include <stdio.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <string.h>int main(){    unsigned long n1 =  inet_addr("10.213.120.1");unsigned long n2 =  inet_addr("172.18.18.1");struct in_addr stAddr1, stAddr2;stAddr1.s_addr = n1;stAddr2.s_addr = n2;printf("%lu\n", n1);    printf("%lu\n", n2);    char *p1 = inet_ntoa(stAddr1);char *p2 = inet_ntoa(stAddr2);    printf("%s\n", p1);    printf("%s\n", p2);    return 0;}
       结果:

taoge@localhost Desktop> g++ test.cpp 
taoge@localhost Desktop> ./a.out 
24696074
17961644
172.18.18.1
172.18.18.1


      为什么是相同的ip呢? 因为在inet_ntoa中static定义, 那为什么知道有static定义呢? 看看inet_ntoa的原型就基本明白了:char *inet_ntoa(struct in_addr in);   要返回char *, 而入参没有char *, 那几乎就是要用static了啊, 看了一下inet_ntoa的实现, 果然如此。

      static引起的不可重入问题, 我们已经讨论过了, 便不过多聊。

      总之, 不可重入函数就是坑, inet_ntoa便是其中之一。





0 0
原创粉丝点击