Posted on 2012-06-21 00:47
魔のkyo 阅读(671)
评论(0) 编辑 收藏 引用
下面是通过Windows API VirtualAlloc VirtualFree实现的内存分配和释放,同时对内存的保护属性进行了设置,使用MyAlloc申请的内存可以在发生向后的越界访问时(大多数的越界情况都是向后的)立即中断,具体是实现并不难,不解释了直接上代码。
void* MyAlloc(size_t size)
{
SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
DWORD pageNum = (size + systemInfo.dwPageSize - 1) / systemInfo.dwPageSize;
DWORD allocSize = (pageNum + 1) * systemInfo.dwPageSize;
char* buf = (char*)VirtualAlloc(NULL, allocSize, MEM_RESERVE, PAGE_NOACCESS);
VirtualAlloc(buf, pageNum * systemInfo.dwPageSize, MEM_COMMIT, PAGE_READWRITE);
return &buf[pageNum * systemInfo.dwPageSize - size];
}
void MyFree(void* p)
{
SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
void* base = (void*)((DWORD)p / systemInfo.dwPageSize * systemInfo.dwPageSize);
VirtualFree(base, 0, MEM_RELEASE);
}