10.3 Auto Variable Allocation and Access

This section discusses allocation of auto variables (those with automatic storage duration). This also includes function parameter variables, which behave like auto variables, as well as temporary variables defined by the compiler.

The auto (short for automatic) variables are the default type of local variable. Unless explicitly declared to be static, a local variable will be made auto. The auto keyword may be used if desired.

The auto variables, as their name suggests, automatically come into existence when a function is executed, then disappear once the function returns. Since they are not in existence for the entire duration of the program, there is the possibility to reclaim memory they use when the variables are not in existence and allocate it to other variables in the program.

The software stack of the PIC32 is used to store all auto variables. Functions are reentrant and each instance of the function has its own area of memory on the stack for its auto and parameter variables, as described below. See 15.1 Software Stack and18.2.3 Initialize Stack Pointer and Heap for more information on the stack.

The compiler dedicates General Purpose Register 29 as the software Stack Pointer. All processor stack operations, including function call, interrupts and exceptions use the software stack. The stack grows downward from high addresses to low addresses.

By default, the size of the stack is 1024 bytes. The size of the stack may be changed by specifying the size on the linker command line using the --defsym_min_stack_size linker command line option. An example of allocating a stack of 2048 bytes using the command line is:

xc32-gcc foo.c -Wl,--defsym,_min_stack_size=2048

The run-time stack grows downward from higher addresses to lower addresses (see the figure below). The compiler uses two working registers to manage the stack:

  • Register 29 (sp) – This is the Stack Pointer. It points to the next free location on the stack.
  • Register 30 (fp) – This is the Frame Pointer. It points to the current function’s frame. Each function, if required, creates a new frame from which automatic and temporary variables are allocated. Compiler optimization may eliminate Stack Pointer references via the Frame Pointer to equivalent references via the Stack Pointer. This optimization allows the Frame Pointer to be used as a General Purpose Register.
Figure 10-1. Stack Frame

The the standard qualifiers const and volatile may both be used with auto variables and these do not affect how they are positioned in memory. This implies that a local const-qualified object is still an auto object and, as such, will be allocated memory on the stack in the data memory, not in the program memory like with non-auto const objects.p

Local Variable Size Limits

There is no theoretical maximum size for auto variables.