ali
ali

Reputation: 11045

Memory status after releasing LPDIRECT3D9 and LPDIRECT3DDEVICE9

This is C++, WINAPI and DirectX.

I create a simple window and it occupies like 1 Mb in the memory (as seen in the Task Manager). When I create the DirectX objects (LPDIRECT3D9 and LPDIRECT3DDEVICE9) it goes to like 10 Mb. After I release those two:

if( pd3dDevice != NULL )  
    pd3dDevice->Release( );
if( pD3D != NULL )  
    pD3D->Release( );`) 

The memory doesn't come back to 1 Mb but to about 3 Mb. So I wonder if there's something else to be done or if this is normal.

Upvotes: 1

Views: 392

Answers (1)

Adam Rosenfield
Adam Rosenfield

Reputation: 400224

This is normal behavior. Typically, when you allocate a lot of memory through a function such as malloc() (or one of many other similar functions), after that memory gets freed, it doesn't get returned immediately to the OS. The allocator will often keep the memory around in a pool under the assumption that the program might want to allocate memory again, so that when it does, it doesn't have to ask the OS for more virtual address space.

So under the hood, here's what usually happens:

  1. Program calls malloc(10*1024*1024) to allocate 10 MB
  2. malloc() calls VirtualAlloc() to allocate 10 MB of virtual address space from the OS.
  3. The OS reports that the program is using 10 MB more virtual memory
  4. The memory is used by the program
  5. Program calls free() to deallocate the 10 MB
  6. free() does NOT call VirtualFree() to return the virtual address space back to the OS.
  7. As far as the program is concerned, the memory is freed and cannot be used again; doing so would be Undefined Behavior. As far as the OS is concerned, the memory is still in use.
  8. If the program later calls malloc(10*1024*1024) again, malloc() can just return that memory again directly without calling VirtualAlloc() to allocate more virtual address space.

Now obviously, the exact behavior depends on which allocator is used by DirectX under the hood. Some allocators will free the memory back to the OS immediately after the program frees it. But my guess is that DirectX is using an allocator which does not do so.

This is just a case of looking at the world through kernel-colored glasses.

Upvotes: 1

Related Questions