最近在写一个网络诊断的小程序,由于粗心大意或说自己的初始化意识不够强,造成了被主管"鄙视"的事态,哈哈。笑完后,告诉自己,以后碰到使用数据结构的地方,就当是碰到指针一样,不管三七二十一,初始化先。
在Debug下不初始化数据结构或句柄啥的没关系,因为Debug下,VC替你做了。但在Release下就会出现不确定的行为。有时可以,时不可以....
比如在CListCtrl中改变图标的一段代码:
1void CPSDiagDlg::ChangeImage(int nItem,int nImg)
2{
3 LVITEM item;
4
5 //memset(&item,0,sizeof(LVITEM));
6 item.iItem = nItem;
7 m_list.GetItem(&item);
8 item.mask = LVIF_IMAGE;
9 item.iImage = nImg;
10 m_list.SetItem(&item);
11} 这段代码在Debug下运行得很好,但在Release却没什么影响,偶尔能改变图标(换图标)。如果把注释掉的5行放开,一切ok.
还有一段发送UDP数据包的代码:
创建sock:
1BOOL CPSSvrTester::CreateSocket(WORD wPort)
2{
3 if (m_socket != INVALID_SOCKET && m_wPort != wPort)
4 {
5 closesocket(m_socket);
6 m_socket = INVALID_SOCKET;
7 }
8 if(m_socket == INVALID_SOCKET)
9 {
10 sockaddr_in local;
11 //wPort = 6002;
12 if(wPort)
13 m_wPort = wPort;
14
15 local.sin_family=AF_INET;
16 local.sin_addr.s_addr=0;
17 local.sin_port=htons(m_wPort);
18
19 WORD wTmpPort = wPort;
20 int iTimes = 0;
21
22 m_socket = socket(AF_INET, SOCK_DGRAM, 0);
23 while(bind(m_socket,(sockaddr *)&local,sizeof(sockaddr_in)) == SOCKET_ERROR)
24 {
25 closesocket(m_socket);
26 iTimes++;
27 if(iTimes>10)
28 break;
29 //m_socket = INVALID_SOCKET;
30 if(wPort)
31 local.sin_port = htons(++wTmpPort);
32 m_socket = socket(AF_INET, SOCK_DGRAM, 0);
33 }
34 if(iTimes<=10)
35 {
36 int inamelen = sizeof(local);
37 if(getsockname(m_socket,(SOCKADDR *)&local,&inamelen ) == SOCKET_ERROR)
38 {
39 closesocket(m_socket);
40 m_socket = INVALID_SOCKET;
41 return FALSE;
42 }
43 m_wPort = ntohs(local.sin_port);
44 }
45 else
46 {
47 closesocket(m_socket);
48 m_socket = INVALID_SOCKET;
49 return FALSE;
50 }
51 int TimeOut=2000;
52 setsockopt (m_socket, SOL_SOCKET,SO_RCVTIMEO,(CHAR *) &TimeOut,sizeof (TimeOut));
53 return TRUE;
54 }
55 return TRUE;
56} 发送UDP数据包的代码:
1BOOL CPSSvrTester::Send(BYTE *pData, DWORD dwDataLen, DWORD dwSendTo, WORD wPort)
2{
3 if (m_socket == INVALID_SOCKET)
4 {
5 return FALSE;
6 }
7 SOCKADDR_IN remote;
8 int iRet;
9 remote.sin_family = AF_INET;
10 remote.sin_port = htons(wPort);
11 remote.sin_addr.s_addr = dwSendTo;
12 iRet = sendto(m_socket,(const char*)pData,dwDataLen,0,(SOCKADDR *)&remote,sizeof(remote));
13 if(iRet<=0)
14 return FALSE;
15 return TRUE;
16} 在Debug下先调用CreateSocket,然后调用Send发送数据,每次都ok.因为Debug,vc已把m_sock初始化为INVALID_SOCKET。而在Release下就完罗,怎么也发不了数据,因为CreateSocket里的代码根本没执行!
在构造函数中添加:m_sock = INVALID_SOCKET;一切ok!
posted on 2006-09-03 00:19
冰风谷 阅读(964)
评论(0) 编辑 收藏 引用 所属分类:
编程中的贝壳