Managing Variables, Stacks, and Heaps on Mobile Devices

Send Feedback

This topic examines important factors about how your application allocates memory to manage static and global variables, stacks, and heaps.

Static and Global Variables

Static and global variables are created when a process starts and cannot be freed until the process ends. Therefore, you should limit your use of static and global variables, especially with large memory allocations and arrays.

Stacks

When a process is created on a Windows Mobile-based Pocket PC, a stack is created for the thread belonging to that process. Likewise, for each new thread that is spawned in the process, a separate stack is created.

To store the values of parameters passed to functions and variables created in functions, the stack provides 58 KB of usable memory. The stack memory used by a function is freed when the function returns.

You cannot create private stacks as you can with heaps. Nor can you increase the size of the stack. Exceeding the 58-KB stack limitation can cause a failure in your application.

Heaps

Each process started on a Windows Mobile-based Pocket PC creates a default heap, which cannot be deleted but is automatically freed when the application process ends. Memory is allocated and freed from the heap through any of the following means:

Whenever you allocate memory, you must check that the allocation succeeded. If your memory allocation fails, you can ask the shell to free additional memory by calling the SHCloseApps function and passing the amount of memory that your application requires.

With repeated allocation and deallocation of memory, the heap becomes fragmented, causing additional memory and address space to be used to make a requested allocation. This effect becomes more pronounced in long-running applications like those typically used on mobile devices.

If your application requires repeated allocation and deallocation of heap memory, you should consider using the Windows CE HeapCreate function to create a private heap in your application. Unlike the default heap, private heaps can be deleted to free all memory on that heap. Deleting private heaps is a good way for an application to respond to the Windows CE WM_HIBERNATE message from the shell.

See Also

Handling Application Hibernation | Handling Low Memory States | How to: Determine Available Memory | How to: Determine Battery Status | Preventing Automatic Power Down | How to: Program Applications to Turn the Smartphone Backlight Off and On | How to: Suspend the Device | Memory and Power Management | Getting Memory Status and Processor Information | System Out of Memory Dialog Box

Send Feedback on this topic to the authors

Feedback FAQs

© 2006 Microsoft Corporation. All rights reserved.