[C++] 纯文本查看 复制代码
LPVOID WINAPI VirtualAlloc(
__in_opt LPVOID lpAddress,
__in SIZE_T dwSize,
__in DWORD flAllocationType,
__in DWORD flProtect
);
[C++] 纯文本查看 复制代码
// VirtualAlloc.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <Windows.h>
#include <locale.h>
int _tmain(int argc, _TCHAR* argv[])
{
setlocale (LC_ALL, "CHS");
SIZE_T sizeVirtual = 4000; // 大小
LPVOID lpRound = (LPVOID)0x100000FF; // 地址
MEMORY_BASIC_INFORMATION mbi; // 内存信息
LPVOID lpAddress = VirtualAlloc(
lpRound,
sizeVirtual,
MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
if (lpAddress == NULL) {
_tprintf (TEXT("VirtualAlloc error : %d\n"), GetLastError());
return (-1);
}
_tprintf (TEXT("Alloc: MEM_COMMIT | MEM_RESERVE\n"));
//复制数据到内存中
CopyMemory (lpAddress, TEXT("Hello Windows"), 2*_tcslen(TEXT("Hello Windows")));
_tprintf (TEXT("分配与内存复制成功,分配地址: 0x%.8x, 复制内容:%s\n"), lpAddress, lpAddress);
//获取内存信息并将其打印
VirtualQuery (lpAddress, &mbi, sizeof(mbi));
_tprintf (TEXT("\n使用 VirtualQuery() 获得的内存信息:\n"));
_tprintf (TEXT( "BaseAddress: 0x%.8x\nAllocationBase: 0x%.8x\nAllocationProtect: 0x%.8x\nRegionSize: %u\nState: 0x%.8x\nProtect: 0x%.8x\nType: 0x%.8x\n"),
mbi.BaseAddress, mbi.AllocationBase, mbi.AllocationProtect, mbi.RegionSize, mbi.State, mbi.Protect, mbi.Type);
//DECOMMIT 释放,页面变为保留状态
_tprintf (TEXT("Free: DECOMMIT\n"));
if (!VirtualFree(lpRound, sizeVirtual, MEM_DECOMMIT)) {
_tprintf (TEXT("VirtualFree() Error: %d\n"), GetLastError());
return (-1);
}
//再次获取内存信息并打印
VirtualQuery (lpAddress, &mbi, sizeof(mbi));
_tprintf (TEXT("\n使用 VirtualQuery() 获得的内存信息:\n"));
_tprintf (TEXT( "BaseAddress: 0x%.8x\nAllocationBase: 0x%.8x\nAllocationProtect: 0x%.8x\nRegionSize: %u\nState: 0x%.8x\nProtect: 0x%.8x\nType: 0x%.8x\n"),
mbi.BaseAddress, mbi.AllocationBase, mbi.AllocationProtect, mbi.RegionSize, mbi.State, mbi.Protect, mbi.Type);
//最后释放内存
_tprintf (TEXT("Free : Release\n"));
if (!VirtualFree(lpAddress, 0, MEM_RELEASE)) {
_tprintf (TEXT("VirtualFree Error : %d\n"), GetLastError());
return (-1);
}
return 0;
}