For what do I need to use VirtualAlloc/VirtualAllocEx?

Alex picture Alex · Jul 7, 2013 · Viewed 9.5k times · Source

For what do I need to use VirtualAlloc/VirtualAllocEx?

An example, one case that I found - if I allocated 4 GB of virtual memory, then if I do not use all of them, then I do not spend physical memory, and if I resize my array, I do not need to do new allocating and copying old data to new array.

struct T_custom_allocator; // which using VirtualAllocEx()
std::vector<int, T_custom_allocator> vec;
vec.reserve(4*1024*1024*1024);  // allocated virtual memory (physical memory is not used)
vec.resize(16384); // allocated 16KB of physical memory
// ...
vec.resize(32768); // allocated 32KB of physical memory 
                   // (no need to copy of first 16 KB of data)

And if I used standard allocator, I need to copy of data when I do resize:

std::vector<int> vec;
vec.resize(16384); // allocated 16KB of physical memory
// ...
vec.resize(32768); // allocated 32KB of physical memory 
                   // and need to copy of first 16 KB of data

Or with standatd allocator, I must spend 4GB of physical memory:

std::vector<int> vec;
vec.reserve(4*1024*1024*1024);  // allocated 4GB of physical memory
vec.resize(16384); // no need to do, except changing a local variable of size
// ...
vec.resize(32768); // no need to do, except changing a local variable of size

But, why this is better than realloc()? http://www.cplusplus.com/reference/cstdlib/realloc/

And are there any else cases to use VirtualAlloc[Ex] with benefits?

Answer

James Holderness picture James Holderness · Jul 7, 2013

Another use for VirtualAllocEx which hasn't been mentioned yet, is to allocate memory in another process' address space. Note that the first parameter is the handle to a process - the function allocates the memory within the virtual address space of that process.

I've used this before when injecting code into another process, by forcing a LoadLibrary call in the target process. The basic steps are as follows:

  1. Get the process id of the target process (e.g. with something like GetWindowThreadProcessId).
  2. Get a handle to the process with the appropriate permissions using OpenProcess.
  3. Allocate some memory in that process with VirtualAllocEx.
  4. Copy the name of your DLL into that memory with WriteProcessMemory.
  5. Get the address of the LoadLibrary function using GetProcAddress.
  6. Call CreateRemoteThread to start the LoadLibrary call in the target process, with the thread parameter being the memory you've allocated with VirtualAllocEx (containing the name of the DLL).

Not that you needed to know all of that, but I though it was an interesting use case.