Search code examples
winapimemory-managementheap-memoryvirtual-memoryfile-mapping

when should I use "Memory Manipulation Mechanisms" in WIN32 API programming?


I am studying WINAPI programming and doing bit kind of experiments by writing winapi codes. When I moved toward 'Memory Management using winapi' topic, I saw there are some 'Memory Manipulation Mechanisms' which is

    Virtual Memory 
    >        LPVOID VirtualAlloc(
             LPVOID lpAddress, 
             SIZE_T dwSize, 
             DWORD  flAllocationType,
             DWORD  flProtect);

    Memory Mapped Files
    >        HANDLE CreateFileMappingA(
             HANDLE                hFile,
             LPSECURITY_ATTRIBUTES lpFileMappingAttributes,
             DWORD                 flProtect,
             DWORD                 dwMaximumSizeHigh,
             DWORD                 dwMaximumSizeLow,
             LPCSTR                lpName
             );

    Heaps
    >        HANDLE HeapCreate(
             DWORD  flOptions,
             SIZE_T dwInitialSize,
             SIZE_T dwMaximumSize
             );


But I unable to understand that, when to use Virtual memory and when to use Heaps mechanism similarly for memory mapped files. what is the real time example for using any of this, or in programmers point of view in which scenario i have to prefer virtual memory,mapped files,heap ?.


Solution

  • Applications generally use two levels of memory allocation. The operating system allocates memory to a process in pages.

    Because applications typically allocate memory in quantities much smaller than a page, they use library functions (such as malloc) to allocate memory from a heap manager. The heap manager in turn allocates memory in pages from the operating system.

    You have examples from both groups of functions. VirtualAlloc and CreateFileMapping allocate pages of memory from the operating system. A virtual memory system requires pages to be backed in secondary storage. CreateFileMapping backs the pages to a file you specify. VirtualAlloc will cause the pages to be backed by a system page file.

    Generally, you use page allocation functions when you need to allocate a large amount of memory, such as a 100MB array for molecular modeling.

    HeapCreate is used to create a heap for smaller memory allocation. HeapAlloc can be used to allocate memory from the heap. More commonly, C programmers just use malloc/free. However, Windoze allows you to define your own heaps for better control. In Eunuchs land, you typically link in your own malloc/free implementation to do the same thing.

    Thus, your first choice is the memory allocation scheme used by the programming language (e.g., new/delete, malloc/free). You second choice is Heap API functions (if the previous do not meet your needs). Your third choice is page allocation functions.