Programming Microsoft Visual C++

If your program needs dynamic memory, sooner or later the Win32 VirtualAlloc function will be called. Chances are that your program will never call VirtualAlloc; instead you'll rely on the Windows heap or the CRT heap functions to call it directly. Knowing how VirtualAlloc works, however, will help you better understand the functions that call it.

First you must know the meanings of reserved and committed memory. When memory is reserved, a contiguous virtual address range is set aside. If, for example, you know that your program is going to use a single 5-MB memory block (known as a region) but you don't need to use it all right away, you call VirtualAlloc with a MEM_RESERVE allocation type parameter and a 5-MB size parameter. Windows rounds the start address of the region to a 64-KB boundary and prevents your process from reserving other memory in the same range. You can specify a start address for your region, but more often you'll let Windows assign it for you. Nothing else happens. No RAM is allocated, and no swap file space is set aside.

When you get more serious about needing memory, you call VirtualAlloc again to commit the reserved memory, using a MEM_COMMIT allocation type parameter. Now the start and end addresses of the region are rounded to 4-KB boundaries, and corresponding swap file pages are set aside together with the required page table. The block is designated either read-only or read/write. Still no RAM is allocated, however; RAM allocation occurs only when you try to access the memory. If the memory was not previously reserved, no problem. If the memory was previously committed, still no problem. The rule is that memory must be committed before you can use it.

You call the VirtualFree function to "decommit" committed memory, thereby returning the designated pages back to reserved status. VirtualFree can also free a reserved region of memory, but you have to specify the base address you got from a previous VirtualAlloc reservation call.

Категории