Memory Usage by C Compiler

This program demonstrates some features of memory usage by the C compiler.

Variables declared inside a function are allocated on the stack, except if they are declared static, in which case they are allocated to data memory. Both mutable (volatile) and immutable (const) local variables are allocated on the stack.

Variables allocated outside of the main program are external variables and are allocated to data memory. If they are declared to be const variables, they are allocated in the read-only program memory.

This example program also shows how to obtain the address of a variable using printf, the %p (pointer) format designator, and the address of (&) operator. See lines 13-17.

C Source

Project source: mem1.zip


01: #include <p32xxxx.h>
02: #include "db_utils.h"
03: 
04: int nd = 1414;
05: 
06: const int ne = 2008;
07: 
08: int main()
09: {
10:         int na;
11:         const int nb = 31415;
12:         static int nc = 0x1234ABCD;
13:         printf("&na = %p\n",&na);
14:         printf("&nb = %p\n",&nb);
15:         printf("&nc = %p\n",&nc);
16:         printf("&nd = %p\n",&nd);
17:         printf("&ne = %p\n",&ne);
18:         DBPUTS("Program terminated. Click HALT and then RESET to stop the microcontroller. \n");
19:         return 0;
20: }


Results

variableaddressremarks
na0xa0007ff0 s8 + 16 (stack)
nb0xa0007ff4 s8 + 20 (stack)
nc0xa00000f8 data memory
nd0xa00000f4 data memory
ne0x9d073f18 program memory (read-only)

Note that only na, nb, and nc appear in the MPLAB Locals window


Maintained by John Loomis, updated Mon Aug 04 22:15:52 2008