1
static vs automatic storage classes
static storage class means variable persists through
the life of the program
automatic storage class means variable exists only
during its scope
When you declare a variable outside any functions,
it has static storage class (global)
When you declare a variable inside a function, it has
automatic storage class, unless you put the static keyword in front of it:
static int a=0; //the value will persist until program exits
Three types of memory allocations
static allocation: for globals and any static
variables in functions
Allocation on the stack: automatic variables
are said to be “allocated on the stack”
Allocation on the heap: dynamic memory
allocation takes memory off the heap (malloc, new)
Static allocation
Initialized static variables are part of the
binary executable. When the program gets loaded into memory, so do these variables
Un-initialized static variables are not part of
the binary exe. They are automatically allocated when the program gets loaded and initialized to 0 (but always initialize your var. anyway).
Either way, they exist from the start of the
program to the finish.
What is the “stack”?
Consider the following simple program:
int funcB(void) { int i2,j2; float f2; i2=j2=2; f2=2.0f; printf("in B\n"); //set break point here return 0; } int funcA(void) { int i,j; float f; i=j=1; f=1.0f; printf("in A\n"); funcB(); return 0; } int main(int argc, char* argv[]) { funcA(); return 0; }