Frank D. Engel, Jr. wrote:
TYPE PtrRec = RECORD realLocation : INTEGER; { the real memory address } refCount : INTEGER { the number of pointers pointing to this record } END;
POINTER = ^PtrRec;
Now when assigning a pointer:
if ptr is not nil then dec(ptr^.refCount); ptr := newAddress; if ptr is not nil then inc(ptr^.refCount);
When derefing:
if ptr^.realLocation = 0 then complain else readValue := ptr^.realLocation
etc, etc... when refCount reaches zero, you can reuse the record. You could turn the record into a linked list structure, and add to the end only when marching through the list during an allocation does not reveal a reusable record.
This adds O(1) to the deref, assignment, and dispose times for a pointer, but makes a slightly larger hit when allocating memory. Since the records can be reused after the refCount hits zero, the memory leak factor is reduced in intensity.
Not necessarily "slightly". O(n) can be large. It can make the difference between a fast and an almost unusable program. Though this particular O(n) can probably avoided -- if the only criterion for reusability is the size, just keeping different sizes in different lists should do it. AFAIK, that's what usual memory managers do as well, of course with the blocks explicitly `free'd. So you probably just as well `free' the memory when the reference count reaches zero and let the memory manager take care of the rest.
You would need to be careful to correctly reduce reference counts from local variables, from pointers inside deallocated record structures and arrays of pointers, arrays of records containing pointers, and so forth.
The coding for this would be somewhat complex, but it may help to achieve what you are calling for...
Again, "somewhat complex" is a "slight" understatement. It would affect all usages of pointers, including in external libraries, which for practical purposes means it's impossible.
Anyway, what you describe, is a form of garbage collection. This is a branch of science on its own. Many algorithms exist, each with their own advantages and disadvantages.
Frank