这个是什么情况,算是bug吗?高手来看看C/C++ code#include WinSock2.h#include iostreamusing namespac
这个是什么情况,算是bug吗?高手来看看
- C/C++ code
#include <WinSock2.h>#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){ in_addr a,b; a.S_un.S_addr=inet_addr("1.1.1.1"); b.S_un.S_addr=inet_addr("2.2.2.2"); cout<<inet_ntoa(a)<<endl<<inet_ntoa(b)<<endl; return 0;}结果输出a和b的都显示为1.1.1.1
如果把cout那一行分成两行写的话,输出就是正确的。
这是什么bug?或者是什么其他原因?
[解决办法]
不是bug,是用法问题
inet_ntoa
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 string returned is guaranteed to be valid only until the next Windows Sockets function call is made within the same thread. Therefore, the data should be copied before another Windows Sockets call is made.
[解决办法]
不是bug,问题出在inet_ntoa()这个函数身上。
好好看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 string returned is guaranteed to be valid only until the next Windows Sockets function call is made within the same thread. Therefore, the data should be copied before another Windows Sockets call is made.
[解决办法]
给个效果相同的例子
- C/C++ code
char* func(int i){ static char buf[]="0.0.0.0"; sprintf(buf,"%d.%d.%d.%d",i,i,i,i); return buf; }int main(){ cout <<func(1) <<endl <<func(2) <<endl; return 0;} 