当前位置: 代码迷 >> 驱动开发 >> 为什么一个简单的申请内存和释放存储出现异常!郁闷
  详细解决方案

为什么一个简单的申请内存和释放存储出现异常!郁闷

热度:105   发布时间:2016-04-28 11:18:51.0
为什么一个简单的申请内存和释放存储出现错误!郁闷!
PUCHAR pTempData = NULL;
Len = 100;
status = NdisAllocateMemoryWithTag(&pTempData,TotalPacketLength + Len,TAG);
if(status != NDIS_STATUS_SUCCESS)
{
status = NDIS_STATUS_FAILURE;
__leave;
}
NdisZeroMemory(pTempData,TotalPacketLength + Len);
NdisMoveMemory(pTempData,pPacketContent,TotalPacketLength);
nNewDataLen = TotalPacketLength + Len;
status = NdisAllocateMemoryWithTag(&pNewPacketContent,TotalPacketLength + Len,TAG);
if(status != NDIS_STATUS_SUCCESS)
{
status = NDIS_STATUS_FAILURE;
__leave;
}
NdisZeroMemory(pNewPacketContent,TotalPacketLength + Len);
NdisMoveMemory(pNewPacketContent,pTempData, sizeof(ETHHDR)+ ip_len + tcp_len);
if (pTempData)NdisFreeMemory(pTempData,TotalPacketLength + Len,0);

为什么此处的 if (pTempData)NdisFreeMemory(pTempData,TotalPacketLength + Len,0); 都出现蓝屏:

BAD_POOL_CALLER (c2)
The current thread is making a bad pool request. Typically this is at a bad IRQL level or double freeing the same allocation, etc.
Arguments:
Arg1: 00000007, Attempt to free pool which was already freed
Arg2: 00000cd4, (reserved)
Arg3: 00000000, Memory contents of the pool block
Arg4: 816099e8, Address of the block of pool being deallocated

POOL_ADDRESS: 816099e8 Nonpaged pool

BUGCHECK_STR: 0xc2_7
LAST_CONTROL_TRANSFER: from 804f880d to 80527da8

STACK_TEXT:  
f9dc70f8 804f880d 00000003 f9dc7454 00000000 nt!RtlpBreakWithStatusInstruction
f9dc7144 804f93fa 00000003 81631130 816099e0 nt!KiBugCheckDebugBreak+0x19
f9dc7524 804f9925 000000c2 00000007 00000cd4 nt!KeBugCheck2+0x574
f9dc7544 80544c86 000000c2 00000007 00000cd4 nt!KeBugCheckEx+0x1b
f9dc7594 f96e660f 816099e8 00000000 f9dc78a0 nt!ExFreePoolWithTag+0x2a0
f9dc75a4 f9ae19a6 816099e8 00000616 00000000 NDIS!NdisFreeMemory+0x3b

------解决方案--------------------
楼主可使用 ExAllocatePoolWithTag 和 ExFreePool这两个函数处理内核内存! 
WDK 描述:
Callers of ExFreePool must be running at IRQL <= DISPATCH_LEVEL. A caller at DISPATCH_LEVEL must have specified a NonPagedXxx PoolType when the memory was allocated. Otherwise, the caller must be running at IRQL <= APC_LEVEL.
也就是说只要是在ExAllocatePoolWithTag 分配内存时是使用 NonPagedPool进行的非分页内存分配,在DISPATCH_LEVEL 进行释放是可以的!
  相关解决方案