Storage Management
Storage Management
The stack
When you enter a subprogram (function,
procedure, method), space is allocated on the
stack for
local variables
formal parameters
Pointers
Allocating storage from the heap is easy
Person p = new Person ( );
References
The Java name for pointers is references
The only real difference is that Java does not
provide (many) operations on pointers
Advantages/disadvantages
Pointers give you:
Greater flexibility and (maybe) convenience
A much more complicated syntax
More ways to create hard-to-find errors
Deallocation
There are two potential errors when
deallocating (freeing) storage yourself:
Deallocating too soon, so that you have
dangling references (pointers to storage that has
been freed and possibly reused for something
else)
Forgetting to deallocate, so that unused storage
accumulates and you have a memory leak
Ownership
If you have to deallocate storage yourself, a
good strategy is that of ownership
The function that owns the storage is
responsible for deallocating it
Ownership can be transferred
You just need a clearly defined policy for
determining ownership
In practice, this is easier said than done
Discipline
Most C/C++ advocates say:
It's just a matter of being disciplined
I'm disciplined, even if other people aren't
Besides, there are good tools for finding
memory problems
However:
Virtually all large C/C++ programs have
memory problems
Garbage collection
Garbage is storage that has been allocated but
is not longer available to the program
It's easy to create garbage; just assign a new
value to the pointer to that storage
A garbage collector automatically searches
out garbage and deallocates it
Practically every modern language, except C+
+, uses a garbage collector
Reference counting
When storage is allocated, make it a bit larger
so it can hold an integer reference count
The reference count keeps track of how many
pointers the program has to the storage
Any assignment to a pointer variable modifies
reference counts
When a reference count reaches zero, the
storage can be garbage collected
The End