Why pointers?

One of the major advantages of pointers is simply performance. Pointers save a lot of copies. A piece of code can access some complex and large structures through a pointer reference. That's the good news. The bad news is that with a pointer reference any piece of code can manipulate the referenced variables and those errors are very hard to find. It also makes life for a garbage collector extremely hard: How should the collector know when a variable is no longer used? An example:


  // allocate memory on the heap to store an Address type
  Address* addressPointer = (Address*) malloc(sizeof struct Address);
 
  fillAddress(addressPointer); // get Address filled in.
  shareAddress(addressPointer); // let others use Address

  free(addressPointer);   // give memory back to heap

So far so good but how does the programmer know when to call "free" to release the memory? What if the function shareAddress has stored the pointer somewhere and tries to use it later? Once "free" is called the memory can be re-used and the results of accessing it with an old pointer are simply undefined. The program can crash quickly or subtle logic problems can appear.