Expert C Programming

(Jeff_L) #1

variables local to its calling function via parameters or global pointers. The runtime maintains a


pointer, often in a register and usually called sp, that indicates the current top of the stack. The stack


segment has three major uses, two concerned with functions and one with expression evaluation:



  • The stack provides the storage area for local variables declared inside functions. These are
    known as "automatic variables" in C terminology.

  • The stack stores the "housekeeping" information involved when a function call is made. This
    housekeeping information is known as a stack frame or, more generally, a procedure
    activation record. We'll describe it in detail a little later, but for now be aware that it includes
    the address from which the function was called (i.e., where to jump back to when the called
    function is finished), any parameters that won't fit into registers, and saved values of registers.

  • The stack also works as a scratch-pad area—every time the program needs some temporary
    storage, perhaps to evaluate a lengthy arithmetic expression, it can push partial results onto


the stack, popping them when needed. Storage obtained by the alloca() call is also on


the stack. Don't use alloca() to get memory that you want to outlive the routine that


allocates it. (It will be overwritten by the next function call.)

A stack would not be needed except for recursive calls. If not for these, a fixed amount of space for
local variables, parameters, and return addresses would be known at compiletime and could be
allocated in the BSS. Early implementations of BASIC, COBOL, and FORTRAN did not permit
recursive calls of functions, so they did not need a dynamic stack at runtime. Allowing recursive calls
means that we must find a way to permit mul-tiple instances of local variables to be in existence at one
time, though only the most recently created will be accessed — the classic specification of a stack.


Programming Challenge


Stack Hack


Compile and run this small test program to discover the approximate location of the stack
on your system:


#include <stdio.h>


main()


{


int i;


printf("The stack top is near %p\n", &i);


return 0;


}


Discover the data and text segment locations, and the heap within the data segment, by
declaring variables that will be placed in those segments and printing their addresses. Make

Free download pdf