Atmel CAVR-4 Manuale Utente

Pagina di 323
CAVR-4
24
The stack and auto variables
AVR® IAR C/C++ Compiler
Reference Guide
The stack is a fixed block of memory, divided into two parts. The first part contains 
allocated memory used by the function that called the current function, and the function 
that called it, etc. The second part contains free memory that can be allocated. The 
borderline between the two areas is called the top of stack and is represented by the stack 
pointer, which is a dedicated processor register. Memory is allocated on the stack by 
moving the stack pointer.
A function should never refer to the memory in the area of the stack that contains free 
memory. The reason is that if an interrupt occurs, the called interrupt function can 
allocate, modify, and—of course—deallocate memory on the stack.
Advantages
The main advantage of the stack is that functions in different parts of the program can 
use the same memory space to store their data. Unlike a heap, a stack will never become 
fragmented or suffer from memory leaks.
It is possible for a function to call itself—a so-called a recursive function—and each 
invocation can store its own data on the stack.
Potential problems
The way the stack works makes it impossible to store data that is supposed to live after 
the function has returned. The following function demonstrates a common 
programming mistake. It returns a pointer to the variable 
x
, a variable that ceases to exist 
when the function returns.
int * MyFunction()
{
  int x;
  ... do something ...
  return &x;
}
Another problem is the risk of running out of stack. This will happen when one function 
calls another, which in turn calls a third, etc., and the sum of the stack usage of each 
function is larger than the size of the stack. The risk is higher if large data objects are 
stored on the stack, or when recursive functions—functions that call themselves either 
directly or indirectly—are used.