Allocating Private Memory

An application can allocate regions of storage within the virtual address space of the process. Such an allocated region is called a memory object.

DosAllocMem is used to allocate a memory object. You specify a variable to receive the pointer that will address the new object, the amount of memory needed, and the allocation attributes and access protection attributes of the new memory object. When choosing the size of the memory object to allocate, remember that the maximum size of the memory object is defined when it is allocated, and memory objects cannot be resized.

When applications call DosAllocMem, the operating system reserves a range of private pages large enough to fulfill the specified allocation request from the private virtual address space of the subject process.

DosAllocMem will reserve this linear space and return zero if the allocation was successful. If it was unsuccessful, DosAllocMem will return an error code. An application should always test the return value before attempting to use the memory.

The following code fragment requests an allocation of 512 bytes. Remember that 4096 bytes will actually be allocated for this request:

    #define  INCL_DOSMEMMGR   /* Memory Manager values */
    #include <os2.h>

    PBYTE   pb;
    APIRET  ulrc;

    ulrc = DosAllocMem((PVOID *) &pb,
                       512,
                       fALLOC); /* pb receives the base address of the */
                                /* 4KB memory object                   */

    if (!ulrc) {           /* If the allocation was successful, ulrc == 0 */
        *pb = 3000;        /* Use the allocated memory                    */
    }

In this example, DosAllocMem returns a 32-bit pointer to a 4096 byte committed memory object and allows the application to write to and read from the memory. This pointer is valid only for the 4096 bytes allocated by the system. An attempt to use the pointer outside the allocated memory will cause a protection violation.


[Back: Using Memory Management]
[Next: Committing and Decommitting Page Ranges]