UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

6.2.  The stack and the local variables

The stack behaves as a space for temporal annotations. For example, when a function is invoked, its local variables are only active during its execution. When the function terminates, these variables do not exist any more. Thus, it makes no sense to reserve space for these variables in the global memory space. In the stack, then, space for variables are created on function beginning and destroyed upon termination. This is the reason why a value produced internally in a function, if it needs to be kept, it is copied either in a global variable, stored using a pointer, or returned as a result, which translates into copying the value in another variable.

The function parameters are also considered local variables. Its scope of validity is identical to the local variables in a function with the exception that they start the execution with an initial value given by the code executing the function call.

The mechanism to pass parameters and return results in a C function can be shown by the operations performed in the stack. Let us assume the there exist a function defined as int function(int a, int b) and it is invoked with the line

result = function(3, x + y);

When the function call is executed a new space in the stack is created to store the function parameters and local variables. On the space allocated for the first parameter a, the value 3 is copied. Analogously, the value resulting from the evaluation of the expression x + y is stored in the space created for the second parameter b. After initializing the parameters with these values the function starts to execute. Note that variables x and y are not necessarily variables visible in the function but they must be valid variables in the code performing the call. The following figure illustrates these operations in the stack.

Once the parameter manipulation in C has been studied, explain why the following function, although it pretends to exchange the values of two variables does not succeed.

Function Call Function definition
...
...
x = 10;
y = 20;
swap(x, y);
printf("x = %d, y = %d\n", x, y);
...
void swap(int a, int b) {
    int tmp;
    tmp = a;
    a = b;
    b = tmp;
    return;
}

How would you redefine function swap such that the swap of the variables has an effect visible outside the function?