11.07.2015 Views

MSP430 IAR C/C++ Compiler reference guide - Rice University

MSP430 IAR C/C++ Compiler reference guide - Rice University

MSP430 IAR C/C++ Compiler reference guide - Rice University

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Data storageAuto variables can only live as long as the function executes; when the function returns,the memory allocated on the stack is released.The stack can contain:● Local variables and parameters not stored in registers●●●Temporary results of expressionsThe return value of a function (unless it is passed in registers)Processor state during interrupts● Processor registers that should be restored before the function returns (callee-saveregisters).The stack is a fixed block of memory, divided into two parts. The first part containsallocated memory used by the function that called the current function, and the functionthat called it, etc. The second part contains free memory that can be allocated. Theborderline between the two areas is called the top of stack and is represented by the stackpointer, which is a dedicated processor register. Memory is allocated on the stack bymoving the stack pointer.A function should never refer to the memory in the area of the stack that contains freememory. The reason is that if an interrupt occurs, the called interrupt function canallocate, modify, and—of course—deallocate memory on the stack.AdvantagesThe main advantage of the stack is that functions in different parts of the program canuse the same memory space to store their data. Unlike a heap, a stack will never becomefragmented or suffer from memory leaks.It is possible for a function to call itself—a so-called recursive function—and eachinvocation can store its own data on the stack.Potential problemsThe way the stack works makes it impossible to store data that is supposed to live afterthe function has returned. The following function demonstrates a commonprogramming mistake. It returns a pointer to the variable x, a variable that ceases to existwhen the function returns.int * MyFunction(){int x;... do something ...return &x;}Part 1. Using the compiler21

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!