当前位置:编程学习 > C/C++ >>

c++堆越界检查范例

堆前向后后向越界检查实例,基本上可以检测不超过一页的堆越界非法读写错误!注意初次申请reservered内存页时,标示它为不可读写,不可执行!

// 越界检查开关
#define SOULCRYSTAL_BOUNDER_CHECK
// 前向越界检查开关
//#define FRONT_ACROSS
// 后向越界检查开关
#define POST_ACROSS
struct tagSoulPig {
tagSoulSpec SoulSpec;
#ifdef SOULCRYSTAL_BOUNDER_CHECK

static size_t Roundup(size_t st,int num=8)
{
return ((st + (num-1)) & ~(num-1));
}

void * operator new ( size_t size )
{
DWORD dwAcSize = 1024* 4 * 2;
PBYTE pStart = (PBYTE)VirtualAlloc(NULL,dwAcSize,MEM_RESERVE,PAGE_NOACCESS);
#ifdef POST_ACROSS
pStart = (PBYTE)VirtualAlloc(pStart,size,MEM_COMMIT,PAGE_READWRITE);
pStart = pStart + 1024* 4 - size;
#elif defined( FRONT_ACROSS )
pStart = (PBYTE)VirtualAlloc(pStart+1024* 4,size,MEM_COMMIT,PAGE_READWRITE);
#endif
return pStart;
}
void operator delete ( void * p )
{
PBYTE pAddr = (PBYTE)p;
#ifdef POST_ACROSS
pAddr -= 1024* 4 - sizeof(tagSoulCrystal);
#elif defined( FRONT_ACROSS )
pAddr -= 1024* 4;
#endif
VirtualFree(pAddr,0,MEM_RELEASE);
}
static void testbounder()
{
tagSoulPig * pTest = new tagSoulPig;
// 正常读写
pTest->SoulSpec.dwSoulStrength = 9;
#ifdef POST_ACROSS
// 向后越界
//int a = pTest->SoulSpec.nSoulAttID[20] ;
pTest->SoulSpec.nSoulAttID[20] = 3;
#elif defined(FRONT_ACROSS)
// 向前越界
int a = 20 - 40;
int v = pTest->SoulSpec.nSoulAttID[a] ;
pTest->SoulSpec.nSoulAttID[a] = 3;
#endif
}
#endif // SOULCRYSTAL_BOUNDER_CHECK
};

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,