首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VC/MFC >

CRITICAL_SECTION用着用着就自己变NULL是怎么回事儿

2013-11-19 
CRITICAL_SECTION用着用着就自己变NULL是咋回事儿?CRITICAL_SECTION mutex//全局...某个地方启动线程AThr

CRITICAL_SECTION用着用着就自己变NULL是咋回事儿?


CRITICAL_SECTION mutex;//全局
...
某个地方启动线程AThreadProc
...
AThreadProc(BYTE *buffer, DWORD size, HWND hDlg)
{
EnterCriticalSection(&mutex);//崩溃的时候都是卡在这的,Debug监视,mutex等于0x0000了!
memcpy(&bufferGlobal[iBufferGlobalEndIndex+1], buffer, size);
iBufferGlobalEndIndex += size;
int iLoop = 0;
BOOL fHasHead = FALSE, fHasTail = FALSE;
int iHeadIndex = 0, iTailIndex = 0;
for (iLoop = iBufferGlobalStartIndex; iLoop < iBufferGlobalEndIndex - 1; iLoop++)
{
if (bufferGlobal[iLoop] == 0x47 && bufferGlobal[iLoop+1] == 0x41)
{
if (fHasHead) /* Before this one is a bad BYTE array. Ignore it. */
{
iBufferGlobalStartIndex = iLoop;
}
fHasHead = TRUE;
iHeadIndex = iLoop;
}
if (bufferGlobal[iLoop] == 0x0A && bufferGlobal[iLoop+1] == 0x0D)
{
fHasTail = TRUE;
iTailIndex = iLoop;
if (fHasHead)
{
CQSCDlg::AnalyseRcvCmd(bufferGlobal + iHeadIndex, iTailIndex - iHeadIndex + 2, NULL, hDlg); 
fHasHead = FALSE;
fHasTail = FALSE;
}
else
{
/* Bad BYTE array, ignore it */  
fHasHead = FALSE;
fHasTail = FALSE;
iHeadIndex = 0;
iTailIndex = 0;
}
iBufferGlobalStartIndex = iLoop + 2;
if (iBufferGlobalStartIndex >= iBufferGlobalEndIndex)
{
iBufferGlobalStartIndex = 0;
iBufferGlobalEndIndex = -1;
break;
}
}
}
if (iBufferGlobalEndIndex - iBufferGlobalStartIndex > 0)
{
memcpy(bufferGlobalBackup, bufferGlobal + iBufferGlobalStartIndex, iBufferGlobalEndIndex - iBufferGlobalStartIndex + 1);
memset(bufferGlobal, 0, 10240);
memcpy(bufferGlobal, bufferGlobalBackup, iBufferGlobalEndIndex - iBufferGlobalStartIndex + 1);
iBufferGlobalStartIndex = 0;
iBufferGlobalEndIndex = iBufferGlobalEndIndex - iBufferGlobalStartIndex;
}
LeaveCriticalSection(&mutex);
return TRUE;
}


除了mutex外,所有带有global字样的变量都是全局的。
整个程序是个读写串口的程序,其中这个AThreadProc就是把每次ReadFile进来的BYTE串拼到这个bufferGlobal里然后截取特定数据头数据尾之间的内容处理。
把程序放着运行一会儿(五分钟左右,有时会更久)就崩溃来了个“不能读取0x0005”,Debug时卡死在函数第一行进入临界区那句,mutex这个时候是NULL(0x0000)。
唯一调用DeleteCriticalSection的地方就是程序退出前。而且打断点了崩溃之前也没断上。
这是怎么回事儿?
[解决办法]
自己变,是不太可能。难道是传说中的越界操作引起的?

热点排行