WaldB
WaldB

Reputation: 1261

Why do allocated blocks in virtual memory vary so much from one run to the other?

I know this may be considered a silly question. But my curiosity is stronger than the fear of downvotes. The code below simply reserves 1GB of the process virtual memory, prints the address of the block reserved and releases the block.

#include <iostream>
#include <Windows.h>

int main()
{
    // Reserves 1GB of the process virtual memory

    LPVOID lp1 = VirtualAlloc((LPVOID)NULL, 0x40000000, MEM_RESERVE, PAGE_NOACCESS);

    std::cout << lp1 << '\n';

    // Releases the 1GB block of virtual memory

    VirtualFree(lp1, NULL, MEM_RELEASE);
}

I run this code in a x64 machine, a few times and obtained the following addresses for lp1:

0x1e 9c22 0000
0xe1 8000 0000
0x16 92a3 0000
0x34 83ec 0000

Why do the addresses vary so much, from one run to the other? I know MS docs don't say anything about this, but I'd like to know if there is some reasonable explanation for this weird behavior?

Upvotes: 3

Views: 109

Answers (2)

Hans Passant
Hans Passant

Reputation: 942000

You probably link with the /DYNAMICBASE linker option, it is turned on by default for x64 projects. Which also gets the /HIGHENTROPYVA option turned on in the executable file header. Run Dumpbin.exe /headers on your EXE file:

OPTIONAL HEADER VALUES
             20B magic # (PE32+)
             ...
           8160 DLL characteristics
                  High Entropy Virtual Addresses     <== here
                  Dynamic base                       <== and here
                  NX compatible
                  Terminal Server Aware

Which asks the memory manager to generate highly random addresses. It makes your program very difficult to attack by malware. Some background in this SE Q+A and highly googable.

Beware that /DYNAMICBASE is also turned on the Debug configuration. While that can be somewhat helpful in getting your program to bomb when it has pointer bugs, it is much more likely to be a massive pain when you have to diagnose such a bug. Don't hesitate to turn it off, it is only intended to protect your program in the wild. Project > Properties > Linker > Advanced > Randomized Base Address = "No".

Upvotes: 4

Prof. Falken
Prof. Falken

Reputation: 24917

There is no reason why it should not differ between allocations, but one popular reason for giving different addresses upon subsequent allocation, is to make security exploits harder to pull off.

The idea is, that exploit code is easier to do if it can know where memory is between program runs. Another reason could be that the different addresses you see is just a side effect of how the allocator keeps track of memory.

Upvotes: 4

Related Questions