0

I'm trying to understand the difference between two ways of reserving virtual memory on Windows.

VOID * AllocateSome( SIZE_T cbSize, VOID * lpDesiredAddress )
{
    HANDLE  handle;
    VOID *  pv;

    // lpDesiredAddress may be NULL.
    // First:
    pv = VirtualAlloc(
        lpDesiredAddress,
        cbSize,
        MEM_RESERVE,
        PAGE_READWRITE );

    // Second:
    handle = CreateFileMappingW(
        INVALID_HANDLE_VALUE,
        NULL,
        ( PAGE_READWRITE | SEC_RESERVE ),
        HighBits(cbSize),
        LowBits(cbSize),
        NULL);

    pv = MapViewOfFileEx(
        handle,
        FILE_MAP_WRITE,
        0,
        0,
        0,
        lpDesiredAddress );

    CloseHandle( handle );

    return pv;
}

Both seem to get a section of virtual address space, reserved but not yet committed, with read+write access, and eventually backed by the pagefile. Are they truly equivalent, or am I missing something?

I'm working on some pre-existing code and both mechanisms are used, but for the life of me I can't figure out why. If there's a difference between the two, MSDN is too subtle for me to get it.

I've read this question: What is difference between virtualAlloc and MapViewOfFile?, but it doesn't address the difference when the file in question isn't really a file in the file system, but rather just a file-shaped piece of the pagefile.

  • Assuming they do the same thing, I figured out why some of the existing code uses the MapViewOfFileEx method. The function I'm looking at does that MapViewOfFileEx inside a loop to get multiple Address Space segments mapped to the same physical memory. I can't see a way to get new VirtualAddress space mapped to the same physical memory if you use VirtualAlloc to get the first mapping. – Tim Williams May 12 '23 at 20:02

0 Answers0