VirtualAlloc MEM_COMMIT and MEM_RESERVE

前端 未结 1 1166
我在风中等你
我在风中等你 2021-01-18 23:48

I\'m little confuse about VirtualAlloc,

We can reserve memory use MEM_RESERVE, and then commit it use MEM_COMMIT, but I\'m little confuse about what the difference

相关标签:
1条回答
  • 2021-01-19 00:13

    The difference is this: with MEM_RESERVE you're basically saying to the operating system: "Hey, please, I need this contiguous block of virtual memory pages, can you give me a memory address that fits my needs?"

    And the operating system calculates where to reserve your block. But it won't allocating nothing yet. (To see how the operating system does this, just look at books like "Windows Internals 5th" by Mark Russinovich -- hint: search on Google about VAD Trees).

    So, when you reserve a block of memory, the operating system will simply allocating a "node" on a tree somewhere, or a structure like that, saying that those addresses are reserved, just like a table at the restaurant, and that cannot be used in other calls to VirtualAlloc().

    Instead, when you actually commit pages with MEM_COMMIT, the operating system is actually allocating virtual memory pages on the block you reserved before. Of course, you can commit pages only on blocks you reserved before. Not doing that is like reserving sits on a restaurant, then take a sit in another table, not reserved by you.

    NOTE: The pages are actually not allocated with committing them neither, since you read/write on them (soft page fault). This is a very useful optimization.

    NOTE2: The fact that you can OR MEM_RESERVE|MEM_COMMIT is just something useful, so you don't have to call the `VirtualAlloc()' API two times, but in fact they remain two very different operations.

    NOTE3: The MEM_COMMIT flag will commit pages on a page size boundary, while using MEM_RESERVE or MEM_RESERVE|MEM_COMMIT will reserve or reserve+commit pages on a boundary greater than the page size, usually 64K on all versions of Windows since today. You can get this number by calling GetSystemInfo().

    0 讨论(0)
提交回复
热议问题