Compartilhar via


Managing Variables, Stacks, and Heaps on Windows Mobile Devices

4/19/2010

Adjusting how you use variables, stacks, and heaps in your Windows Mobile application can save memory space and process time for the application.

Static and Global Variables

Static and global variables are created when an application process starts; these variables cannot be freed until the process ends. Therefore, we recommend that you limit the use of static and global variables, especially when the process involves arrays or large allocations of memory.

Stacks

When an application process is created in Windows Mobile Classic or Windows Mobile Professional, a stack is created for the thread that belongs to the process. Likewise, a separate stack is created for each new thread that is created by the process.

To store the values of parameters that are passed to functions and the values of variables that are created in functions, the stack provides 58 KB of usable memory. This memory is freed when the function returns.

You cannot create private stacks, nor can you increase the size of the stack. Exceeding 58 KB of memory might cause your application to fail.

Heaps

Each application process that starts in Windows Mobile Classic or Windows Mobile Professional creates a default heap that cannot be deleted, although the heap is freed automatically when the process terminates. Any of the following can allocate or free memory from the heap:

Whenever you allocate memory to a heap, make sure that the allocation succeeded. If memory allocation fails, free additional memory from the shell by calling the SHCloseApps function and passing the amount of memory that your application requires.

With repeated reallocation and freeing of memory, the heap becomes fragmented. This results in the loss of even more memory and address space because more space is required each time you request a reallocation of memory. Therefore, the effect is more pronounced in long-running applications like the ones that are often used on mobile devices.

If your application requires repeated reallocation and freeing of heap memory, consider using the HeapCreate function to create a private heap in the application. Unlike a default heap, a private heap can be deleted, which frees all of the memory on the heap. For example, deleting private heaps is a good way for an application to respond to a WM_HIBERNATE message from the shell.

See Also

Concepts

Handling Application Hibernation
Handling Low Memory States
How to: Determine Available Memory
How to: Determine Available Memory
How to: Determine Battery Status
Preventing Automatic Power Down
How to: Program an Application for Windows Mobile Standard to Turn the Backlight On or Off
How to: Suspend the Device
Getting Memory Status and Processor Information
System Out of Memory Dialog Box

Other Resources

Memory and Power Management