vc多线程中使用cstring,运行时程序出错退出
我在做一个网络扫描程序,出现一个很奇怪的现象。
在主进程A中起了10个线程进行扫描,调用B.h
B.h
UINT scan(LPVOID pParam)
{
INFO* info=new INFO();
info=NULL;
info=(INFO*)pParam;
CInput* p=new CInput();
p=NULL;
p=(CInput*)info->ptr;
int PortS=info->PortS;//起始端口
int PortE=info->PortE;//结束端口
CString tmp="",PN;
SOCKET sockd;
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD( 2, 0 );
if ( WSAStartup( wVersionRequested, &wsaData ) != 0 )
{
AfxMessageBox("Can not initial winsock!",NULL,MB_OK);
}
//下面填充socket结构
local.sin_addr.s_addr=htonl(INADDR_ANY);//inet_addr("202.101.166.5");
local.sin_family=AF_INET;
local.sin_port=0;
remote=info->IpAddr;
remote.sin_family=AF_INET;
int len=sizeof(remote);
int act=-100;
//int err;
ULONG argp=1;
int tt;
char error;
tt = sizeof(int);
timeval tm;
fd_set set;
int i;
for(i=PortS;i<PortE;i++)
{
count+=1;
screenCount="processing IP: ";
screenCount+=inet_ntoa(remote.sin_addr);//清空输出窗口显示内容
tmp.Format("%d",i);
screenCount+="\r\n 正在扫描的端口号:"+tmp;
tmp.Format("%d",count);
screenCount+="\r\n 本IP已扫描端口数: "+tmp;
tmp.Format("%d",portAmount);
screenCount+="\r\n 本IP需扫描的端口总数:"+tmp;
p->m_cAllOutput.SetWindowText(screenCount);
remote.sin_port=htons(i);//htons(i)
sockd=socket(AF_INET,SOCK_STREAM,0);//IPPROTO_TCP不能用
ioctlsocket(sockd,FIONBIO,&argp);//设置socket为非阻塞模式
int berr=bind(sockd,(LPSOCKADDR)&local,sizeof(local));
if(berr==SOCKET_ERROR)
{
DWORD aa=GetLastError();
tmp.Format("%d",aa);
AfxMessageBox("Bind error",NULL,MB_OK);
// AfxMessageBox(tmp,NULL,MB_OK);
}
if(sockd<0)
{
AfxMessageBox("socket error",NULL,MB_OK);
}
if( connect(sockd,(struct sockaddr *)&remote,len)==-1)
{
tm.tv_usec =200;//毫秒
tm.tv_sec = 1;//秒
FD_ZERO(&set);
FD_SET(sockd, &set);
if( select(sockd+1, NULL, &set, NULL, &tm) > 0)
{
getsockopt(sockd,SOL_SOCKET,SO_ERROR,&error,&tt);
if(error ==0) act = 0;
else act = -100;
}
else act = -100;
}
else act=0;
if(act==0)
{
n++;//端口数加1
tmp.Format("%d",n);
str+="TCP端口号"+tmp+": ";
tmp.Format("%d",i);
str+=tmp;
PN="http (World Wide Web HTTP)";
出错点: str+=tmp+" "+PN+"\r\n";//只要使用这句,程序就会出错退出,这是为什么???
switch(i)
{
case 7:
PN="echo (ECHO)";
break;
case 9:
PN="discard (Discard)";
break;
default:
PN="****协议名称等待加入中****";
break;
}
str+=" "+tmp+" "+"\r\n";
}
closesocket(sockd);
}//对应 for(int i=PortS;i<PortE;i++)
WSACleanup();
return 0;
}
上面有个很奇怪的现象,只要使用PN,程序就会运行出错退出,但是将PN替换成tmp,那就运行正常,奇了怪了,这是什么原因???怎么解决。