CS360 Midterm Exam. March 14, 2013


Question 1 -- You knew it was coming

Below to the left is the C code for a procedure q1(). Below to the right are the values of 100 bytes of memory starting at address 0x100130. Each value is printed as a four-byte decimal and as a four byte hexadecimal number. The procedure was compiled with four-byte pointers by using the -m32 compilation flag.

struct dllist {
  struct dllist *flink;
  struct dllist *blink;
  int val;
};

typedef unsigned int UI;

void q1(struct dllist *head, unsigned int *a, unsigned int **b)
{
  int i, j;
  struct dllist *p;

  printf("Head: 0x%x  A: 0x%x  B: 0x%x\n", (UI) head, (UI) a, (UI) b);
  printf("\n");

  for (i = 0; i < 3; i++) printf("A[%d]: %d\n", i, a[i]);
  printf("\n");

  for (i = 0; i < 3; i++) {
    printf("B[%d]: 0x%x\n", i, (UI) b[i]);
    for (j = 0; j < 3; j++) {
      printf("B[%d][%d]: %d\n", i, j, b[i][j]);
    }
    printf("\n");
  }

  p = head;
  for (i = 0; i < 3; i++) {
    p = p->flink;
    printf("%d: p: 0x%x  p->val: %d\n", i, (UI) p, p->val);
  }

  printf("\n");
  for (i = 0; i < 3; i++) {
    p = p->blink;
    printf("%d: p: 0x%x  p->val: %d\n", i, (UI) p, p->val);
  }
}

              Value as      Value as
Address        Integer        Hex
--------       -------      --------
0x100130       1048952      0x100178
0x100134       1048928      0x100160
0x100138       1048944      0x100170
0x10013c       1048972      0x10018c
0x100140       1048948      0x100174
0x100144       1048940      0x10016c
0x100148       1048936      0x100168
0x10014c       1048968      0x100188
0x100150       1048956      0x10017c
0x100154       1048944      0x100170
0x100158       1048948      0x100174
0x10015c       1048896      0x100140
0x100160       1048912      0x100150
0x100164       1048896      0x100140
0x100168       1048880      0x100130
0x10016c       1048904      0x100148
0x100170       1048952      0x100178
0x100174       1048956      0x10017c
0x100178       1048924      0x10015c
0x10017c       1048936      0x100168
0x100180       1048884      0x100134
0x100184       1048940      0x10016c
0x100188       1048912      0x100150
0x10018c       1048932      0x100164
0x100190       1048912      0x100150

When q1() executes, the first line of output is:

Head: 0x100130  A: 0x10013c  B: 0x100158
Give me the output of the remainder of the procedure.

Question 2 -- Nuts and Bolts

Write a program that prints the second-to-last line of a file. If the file has zero or one lines, have it print nothing. You may use any of the components of the fields library. Your program should not have memory leaks.