Saturday, May 3, 2008


Running your brew application on a device is entirely different than that on a simulator. Memory stack plays a prominent role in it.

Stack Usage



With BREW™, each running program has a call stack and a heap. Each has a finite maximum amount of space. If the heap cannot be expanded without exceeding the maximum space for it, memory allocation attempts fail; an application should detect this and deal with it as gracefully as possible. However, if the stack expands past its maximum (called "smashing the stack") data is overwritten. This can cause seemingly random and often strange bugs or crashes. Smashing the stack can be a very difficult problem to debug, because it may be data-dependent, won't occur in the emulator, and the code may look fine.

Be sure to keep your stack size below 500 bytes.

To reduce your stack size, try to keep the calling depth short (avoid recursion or deeply nested function calls). Also, except for simple items such as ints, pointers, and other scaler types, consider allocating memory dynamically instead of on the stack. For example, to avoid declaring a buffer inside a function, declare a pointer and dynamically allocate the buffer. (To further reduce memory usage and object code size, you may want to use a global buffer instead of local buffers in multiple functions.)

One method of reducing call depths is to manually unroll your code (taking the code from functions that would otherwise be called and inserting it into a function that would otherwise call it).

Another is to use the INLINE specification with function declarations. However, be aware that compilers may not honor an INLINE directive. For example, as of this writing, the ARM C compiler is reported to ignore INLINE. Use the ARM C++ compiler instead (even if you are writing normal C code). Also, many compilers do not inline functions that are called from outside the file in which they are declared.

The following examples show how to prevent smashing of the stack due to String variables , large structures, and recursion.

No comments: