一个关于inet_ntoa函数在printf中的奇怪现象(不知算不算linux的bug:-)
来源: 互联网 发布时间:2015-10-30
本文导语: 测试代码如下 include #include #include #include #include int main(int aargc, char* argv[]) { struct in_addr addr1,addr2; ulong l1,l2; l1= inet_addr("192.168.0.74"); l2 = inet_addr("211.100.21.1...
测试代码如下
include
#include
#include
#include
#include
int main(int aargc, char* argv[])
{
struct in_addr addr1,addr2;
ulong l1,l2;
l1= inet_addr("192.168.0.74");
l2 = inet_addr("211.100.21.179");
memcpy(&addr1, &l1, 4);
memcpy(&addr2, &l2, 4);
printf("%s : %sn", inet_ntoa(addr1), inet_ntoa(addr2)); //注意这一句的运行结果
printf("%sn", inet_ntoa(addr1));
printf("%sn", inet_ntoa(addr2));
return 0;
}
实际运行结果如下:
192.168.0.74 : 192.168.0.74 //从这里可以看出,printf里的inet_ntoa只运行了一次。
192.168.0.74
211.100.21.179
不知哪位兄弟能给出一个清楚的原因解释?。
本贴纯为讨论之用,故此暂时无分,待有结论后我会把分加上的。
我的测试环境是 linux as3系统,也麻烦兄弟们在其他unix系统下测试一下,谢谢!
include
#include
#include
#include
#include
int main(int aargc, char* argv[])
{
struct in_addr addr1,addr2;
ulong l1,l2;
l1= inet_addr("192.168.0.74");
l2 = inet_addr("211.100.21.179");
memcpy(&addr1, &l1, 4);
memcpy(&addr2, &l2, 4);
printf("%s : %sn", inet_ntoa(addr1), inet_ntoa(addr2)); //注意这一句的运行结果
printf("%sn", inet_ntoa(addr1));
printf("%sn", inet_ntoa(addr2));
return 0;
}
实际运行结果如下:
192.168.0.74 : 192.168.0.74 //从这里可以看出,printf里的inet_ntoa只运行了一次。
192.168.0.74
211.100.21.179
不知哪位兄弟能给出一个清楚的原因解释?。
本贴纯为讨论之用,故此暂时无分,待有结论后我会把分加上的。
我的测试环境是 linux as3系统,也麻烦兄弟们在其他unix系统下测试一下,谢谢!
|
inet_ntoa返回一个char *,而这个char *的空间是在inet_ntoa里面静态分配的,所以inet_ntoa后面的调用会覆盖上一次的调用。第一句printf的结果只能说明在printf里面的可变参数的求值是从右到左的,仅此而已。
So, you are wrong but the result is right.: )
So, you are wrong but the result is right.: )
|
呵呵,inet_ntoa是不可重入函数啊。。。里面用了静态变量。建议用inet_ntop来代替。
|
Linux:
The inet_ntoa() function converts the Internet host address in given in network byte order to a string in standard numbers-and-dots notation. The string is returned in a statically allocated buffer, which subsequent calls will overwrite.
MSDN:
The string returned by inet_ntoa resides in memory that is allocated by Windows Sockets. The application should not make any assumptions about the way in which the memory is allocated. The data is guaranteed to be valid until the next Windows Sockets function call within the same thread—but no longer. Therefore, the data should be copied before another Windows Sockets call is made.
The inet_ntoa() function converts the Internet host address in given in network byte order to a string in standard numbers-and-dots notation. The string is returned in a statically allocated buffer, which subsequent calls will overwrite.
MSDN:
The string returned by inet_ntoa resides in memory that is allocated by Windows Sockets. The application should not make any assumptions about the way in which the memory is allocated. The data is guaranteed to be valid until the next Windows Sockets function call within the same thread—but no longer. Therefore, the data should be copied before another Windows Sockets call is made.
|
不怕泄漏的,strdup 之~