Comp210 Lab 14: Danger: Mixing struct* and struct

The confusion arises when you start mixing structures with pointers-to-structures. For instance, here is code with a subtle bug:
struct Cons {
  int car;
  Cons* cdr;
  }

Cons* badMakeCons( int datum, Cons* rest ) {
  Cons newFront;  // NOTE: a Cons, not a Cons*.
                  // Therefore don't use "new", since space is allocated for us.
  newFront.car = datum;
  newFront.cdr = rest;
  return &newFront;
  }

int main() {
  Cons* newList = badMakeCons( 5, NULL );
  // ... newList may now point to bad things!
  return 0;
  }
The problem is, the function badMakeCons returns a pointer to the memory where newFront resides. But since newFront ceases to exist after leaving the function (after all it was a local variable), the pointer which is returned is now pointing at invalid memory, thus using newList can case a segmentation fault!

To make things worse, the invalid memory for the moment happens to have the correct values in it, so for a bit newList might seem to work fine. (When badMakeCons finishes, the memory for newFront simply is tagged as unused, but there's no need to actually clean out the old values.) But eventually, when the computer needs more memory, it will re-use the memory once occupied by newFront, changing those values, and much later newList seems to suddenly mysteriously change. Tracing the error is certified to drive you insane.


Back to Lab 14
Back to Comp 210 Home