Using Memory

The Windows memory-management system lets your application allocate blocks of memory. You can allocate blocks of memory from either the global or the local heap. The global heap is a pool of free memory available to all applications. The local heap is a pool of free memory available to just your application. In managing the system memory, Windows also manages the code and data segments of your application.

Summary: The Windows memory manager can move and discard memory blocks as needed.

In some memory-management systems, the memory you allocate remains fixed at a specific memory location until you free it. In Windows, allocated memory can also be movable and discardable. A movable memory block does not have a fixed address; Windows can move it at any time to a new address. Movable memory blocks let Windows make the best use of free memory. For example, if a movable memory block separates two free blocks of memory, Windows can move the movable block to combine the free blocks into one contiguous block. A discardable memory block is similar to movable memory in that windows can move it, but Windows can also reallocate a discardable block to zero length if it needs the space to satisfy an allocation request. Reallocating a memory block to zero length destroys the data the block contains, but an application always has the option of reloading the discarded data whenever it is needed.

When you allocate a memory block, you receive a handle, rather than a pointer, to that memory block. The handle identifies the allocated block. You use it to retrieve the block's current address when you need to access the memory.

To access a memory block, you lock the memory handle. This temporarily fixes the memory block and returns a pointer to its beginning. While a memory handle is locked, Windows cannot move or discard the block. Therefore, after you have finished using the block, you should unlock the handle as soon as possible. Keeping a memory handle locked makes Windows' memory management less efficient and can cause subsequent allocation requests to fail.

Windows lets you compact memory. By squeezing the free memory from between allocated memory blocks, Windows collects the largest contiguous free-memory block possible, from which you may allocate additional blocks of memory. This squeezing is a process of moving and (if necessary) discarding memory blocks. Windows also lets you discard individual memory blocks if you temporarily have no need for them.