CS 61C (Fall 2011)

Lab Assignment 4

Goals

These exercises are intended to give you more practice with function calling—in particular, what goes onto the stack— plus an introduction to logic operators.

Reading

Sections 2.6-2.8 in P&H (4th).

Initial preparation

You must work with a partner on these exercises.

Copy the directory ~cs61c/labs/04 to an appropriate directory under your home directory.

Exercise 1

The file swap.s provides a test call to the code you'll be supplying for this exercise.

Part a

Translate the following procedure directly to MIPS assembly language. The temp variable, like all local variables in C (when not optimized), is stored on the stack. In other words you cannot use $t0 to hold temp, though you may need it briefly. Hint: you will need to use 6 lw/sw instructions.

This exercise is slightly contrived, and could be easier if we let you optimize and use $t0 to hold the temp variable. Part of the point of this exercise is to see what kind of difference optimization can make.

void swap (int *px, int *py) {
    int temp;
    temp = *px;
    *px = *py;
    *py = temp;
}

Part b

Now modify your solution to the previous step to implement the following buggy version of the swap procedure.

void swap (int *px, int *py) {
    int *temp;
    *temp = *px;
    *px = *py;
    *py = *temp;
}

Part c

What was the bug? What situation would allow this buggy swap to seem to work correctly?

Part d

Supply the definition of a C procedure proc to be called in the main program immediately prior to the call to the buggy swap(as shown below), that will guarantee that swap will crash when the uninitialized temp pointer is dereferenced (it should cause a crash on *temp). Also explain why your call guarantees this crash. Hint: your proc procedure will leave something on the stack.

int main () {
    int a = 1, b = 2;
    proc(/* Some args might go here */);
    swap(&a, &b);
}

Explain all your code to your TA for checkoff.

Exercise 2

Add the prologue and epilogue to the code in nchoosek.s so that it computes "n choose k," the number of combinations that can made from n distinct elements taken k at a time. (This is also the (n,k) entry in Pascal's triangle.)

Show your test run to your TA for checkoff.