CS360 Final Exam. Question 1

17 points

December 13, 1997

This question concerns the doubly-linked list library. Behold the main typedef, plus the code for make_dl(), dl_insert_b(), and dl_delete_node():
typedef struct dlist {
  struct dlist *flink;
  struct dlist *blink;
  void *val;
} *Dlist;

Dlist make_dl()                                /* Creates an empty dlist */
{
  Dlist d;

  d = (Dlist) malloc (sizeof(struct dlist));
  d->flink = d;
  d->blink = d;
  d->val = (void *) 0;
  return d;
}

dl_insert_b(node, val)                   /* Inserts before a given node */
Dlist node;
void *val;
{
  Dlist last_node, new;

  new = (Dlist) malloc (sizeof(struct dlist)); /* create the new node */
  new->val = val;

  last_node = node->blink;

  node->blink = new;                        /* Hook it into the list */
  last_node->flink = new;
  new->blink = last_node;
  new->flink = node;
}

dl_delete_node(item)            /* Deletes an arbitrary node */
Dlist item;
{
  item->flink->blink = item->blink;
  item->blink->flink = item->flink;
  free(item);
}

Part 1

Suppose you have a dlist with 1,000,000 nodes (including the sentinel node), on a machine like our suns (e.g. hydra, cetus). How much memory does that dlist actually consume? (include malloc()'s bookkeeping, but don't worry about external fragmentation).

Part 2

A colleague says to you ``you could have two val fields and it wouldn't cost you anything.'' State why this is a true statement on our machines, but might not be a true statement on other machines.

Part 3

Rewrite the dlist library so that it makes better use of memory. Specifically, make it so that it only calls malloc() once for every 1000 calls to make_dl()/dl_insert_b(). You can use global variables. Make sure dl_delete_node() works with your scheme.

Part 4

Suppose you have a dlist, created with your code from Part 3, with 1,000,000 nodes (including the sentinel node), on a machine like our suns (e.g. hydra, cetus). How much memory does that dlist now consume?