请教一个API VirtualAlloc
最近看windows核心编程 有讲到这个API,于是我就在我们代码里搜了一下,有几个问题想确认一下,请大家指导- -|
1. VirtualAlloc这个函数是分配虚拟地址和物理内存的,如果我想知道它和new有什么区别?如果用VirtualAlloc直接分配物理地址(MEM_COMMIT | MEM_RESERVE),并且是PAGE_READWRITE,然后把这一块内存转成我想要的类型,比如BYTE *那跟用new有什么不一样呢? 这里不讨论new和VirtualAlloc的内部实现的区别。两者之间在速度上有明显区别吗?或者在得到的内存块上有什么区别?
2. VirtualAlloc在获得真实的物理内存的时候是需要MEM_COMMIT的,在调用MEM_COMMIT之前必须要MEM_RESERVE吗?或者必须MEM_COMMIT | MEM_RESERVE码?不能直接给它一个MEM_COMMIT参数吗?跟先给它一个MEM_RESERVE参数或者MEM_COMMIT | MEM_RESERVE有什么区别?
谢谢了
[解决办法]
VirtualAlloc => Allocates straight into virtual memory, you reserve/commit in blocks. This is great for large allocations, for example large arrays.
HeapAlloc / new => allocates the memory on the default heap (or any other heap that you may create). This allocates per object and is great for smaller objects. The default heap is serializable therefore it has guarantee thread allocation (this can cause some issues on high performance scenarios and that's why you can create your own heaps).
malloc => uses the C runtime heap, similar to HeapAlloc but it is common for compatibility scenarios.
In a nutshell, the heap is just a chunk of virtual memory that is governed by a heap manager (rather than raw virtual memory)
the last model on the memory world is memory mapped files, this scenario is great for large chunk of data (like large files). This is used internally when you open an EXE (it does not load the EXE in memory, just creates a memory mapped file).
[解决办法]
new隶属于C++语言,不仅分配对象内存空间,还自动调用对象构造函数。
VirtualAlloc隶属于Windows,仅分配虚拟内存,不调用任何构造函数。
Memory Management Functions
The following functions are used in memory management.
CopyMemory
FillMemory
GetProcessHeap
GetProcessHeaps
GlobalMemoryStatus
HeapAlloc
HeapCompact
HeapCreate
HeapDestroy
HeapFree
HeapLock
HeapReAlloc
HeapSize
HeapUnlock
HeapValidate
HeapWalk
IsBadCodePtr
IsBadReadPtr
IsBadStringPtr
IsBadWritePtr
MoveMemory
VirtualAlloc
VirtualAllocEx
VirtualFree
VirtualFreeEx
VirtualLock
VirtualProtect
VirtualProtectEx
VirtualQuery
VirtualQueryEx
VirtualUnlock
ZeroMemory
VLM Functions
CopyMemoryVlm
FillMemoryVlm
GlobalMemoryStatusVlm
MapViewOfFileVlm
MoveMemoryVlm
ReadFileVlm
ReadProcessMemoryVlm
UnmapViewOfFileVlm
VirtualAllocVlm
VirtualFreeVlm
VirtualProtectVlm
VirtualQueryVlm
WriteFileVlm
WriteProcessMemoryVlm
ZeroMemoryVlm
Global and Local Functions
GlobalAlloc
GlobalDiscard
GlobalFlags
GlobalFree
GlobalHandle
GlobalLock
GlobalReAlloc
GlobalSize
GlobalUnlock
LocalAlloc
LocalDiscard
LocalFlags
LocalFree
LocalHandle
LocalLock
LocalReAlloc
LocalSize
LocalUnlock
DWORD dwSize, // size of region
DWORD flAllocationType,
// type of allocation
DWORD flProtect // type of access protection
);
Parameters
lpAddress
Specifies the desired starting address of the region to allocate. If the memory is being reserved, the specified address is rounded down to the next 64-kilobyte boundary. If the memory is already reserved and is being committed, the address is rounded down to the next page boundary. To determine the size of a page on the host computer, use theGetSystemInfo function. If this parameter is NULL, the system determines where to allocate the region.
dwSize
Specifies the size, in bytes, of the region. If the lpAddress parameter is NULL, this value is rounded up to the next page boundary. Otherwise, the allocated pages include all pages containing one or more bytes in the range from lpAddress to (lpAddress+dwSize). This means that a 2-byte range straddling a page boundary causes both pages to be included in the allocated region.
flAllocationType
Specifies the type of allocation. You can specify any combination of the following flags: Flag Meaning
MEM_COMMIT Allocates physical storage in memory or in the paging file on disk for the specified region of pages.
An attempt to commit an already committed page will not cause the function to fail. This means that a range of committed or decommitted pages can be committed without having to worry about a failure.
MEM_RESERVE Reserves a range of the process's virtual address space without allocating any physical storage. The reserved range cannot be used by any other allocation operations (the malloc function, the LocalAlloc function, and so on) until it is released. Reserved pages can be committed in subsequent calls to the VirtualAlloc function.
MEM_RESET Windows NT: Specifies that memory pages within the range specified by lpAddress and dwSize will not be written to or read from the paging file.
When you set the MEM_RESET flag, you are declaring that the contents of that range are no longer important. The range is going to be overwritten, and the application does not want the memory to migrate out to or in from the paging file.
Setting this flag does not guarantee that the range operated on with MEM_RESET will contain zeroes. If you want the range to contain zeroes, decommit the memory and then recommit it.
When you set the MEM_RESET flag, the VirtualAlloc function ignores the value of fProtect. However, you must still set fProtect to a valid protection value, such as PAGE_NOACCESS.
VirtualAlloc returns an error if you set the MEM_RESET flag and the range of memory is mapped to a file. A shared view is only acceptable if it is mapped to a paging file.
MEM_TOP_DOWN Allocates memory at the highest possible address.
flProtect
Specifies the type of access protection. If the pages are being committed, any one of the following flags can be specified, along with the PAGE_GUARD and PAGE_NOCACHE protection modifier flags, as desired: Flag Meaning
PAGE_READONLY Enables read access to the committed region of pages. An attempt to write to the committed region results in an access violation. If the system differentiates between read-only access and execute access, an attempt to execute code in the committed region results in an access violation.
PAGE_READWRITE Enables both read and write access to the committed region of pages.
PAGE_EXECUTE Enables execute access to the committed region of pages. An attempt to read or write to the committed region results in an access violation.
PAGE_EXECUTE_READ Enables execute and read access to the committed region of pages. An attempt to write to the committed region results in an access violation.
PAGE_EXECUTE_READWRITE Enables execute, read, and write access to the committed region of pages.
PAGE_GUARD Pages in the region become guard pages. Any attempt to read from or write to a guard page causes the system to raise a STATUS_GUARD_PAGE exception and turn off the guard page status. Guard pages thus act as a one-shot access alarm.
The PAGE_GUARD flag is a page protection modifier. An application uses it with one of the other page protection flags, with one exception: It cannot be used with PAGE_NOACCESS. When an access attempt leads the system to turn off guard page status, the underlying page protection takes over.
If a guard page exception occurs during a system service, the service typically returns a failure status indicator.
PAGE_NOACCESS Disables all access to the committed region of pages. An attempt to read from, write to, or execute in the committed region results in an access violation exception, called a general protection (GP) fault.
PAGE_NOCACHE Allows no caching of the committed regions of pages. The hardware attributes for the physical memory should be specified as "no cache." This is not recommended for general usage. It is useful for device drivers; for example, mapping a video frame buffer with no caching. This flag is a page protection modifier, only valid when used with one of the page protections other than PAGE_NOACCESS.
Return Values
If the function succeeds, the return value is the base address of the allocated region of pages.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Remarks
VirtualAlloc can perform the following operations:
Commit a region of pages reserved by a previous call to the VirtualAlloc function.
Reserve a region of free pages.
Reserve and commit a region of free pages.
You can use VirtualAlloc to reserve a block of pages and then make additional calls to VirtualAlloc to commit individual pages from the reserved block. This enables a process to reserve a range of its virtual address space without consuming physical storage until it is needed.
Each page in the process's virtual address space is in one of three states:
State Meaning
Free The page is not committed or reserved and is not accessible to the process. VirtualAlloc can reserve, or simultaneously reserve and commit, a free page.
Reserved The range of addresses cannot be used by other allocation functions, but the page is not accessible and has no physical storage associated with it. VirtualAlloc can commit a reserved page, but it cannot reserve it a second time. The VirtualFree function can release a reserved page, making it a free page.
Committed Physical storage is allocated for the page, and access is controlled by a protection code. The system initializes and loads each committed page into physical memory only at the first attempt to read or write to that page. When the process terminates, the system releases the storage for committed pages. VirtualAlloc can commit an already committed page. This means that you can commit a range of pages, regardless of whether they have already been committed, and the function will not fail. VirtualFree can decommit a committed page, releasing the page's storage, or it can simultaneously decommit and release a committed page.
If the lpAddress parameter is not NULL, the function uses the lpAddress and dwSize parameters to compute the region of pages to be allocated. The current state of the entire range of pages must be compatible with the type of allocation specified by the flAllocationType parameter. Otherwise, the function fails and none of the pages are allocated. This compatibility requirement does not preclude committing an already committed page; see the preceding list.
The PAGE_GUARD protection modifier flag establishes guard pages. Guard pages act as one-shot access alarms. For more information, see Creating Guard Pages.
QuickInfo
Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
See Also
Memory Management Overview, Memory Management Functions, GlobalAlloc, HeapAlloc, VirtualAllocVlm, VirtualFree, VirtualLock, VirtualProtect, VirtualQuery