Subject: Re: Heap heaping up?

From: Jan Wielemaker <[email-masked]>
Date: Fri, 9 Jun 2000 13:37:10 +0200

On Fri, 09 Jun 2000, Paul Sephton wrote:
>When I run the following program, the heap just keeps getting bigger.  
>Does the garbage collector have a memory leak?

The garbage collector doesn't do anything to the heap, it only
affects the global- and trail-stacks.  Besides, the control-structure
is failure driven, so all data created on the stacks in each iteration
is destroyed anyhow on backtracking.

It seems there is a memory-leak in consult.  This doesn't really
surprise me.  Consult is for loading sources and it does a lot of
bookkeeping to deal with editing, re-consult, etc.  A small amount
of leakage isn't too bad as source-files are loaded only once, or
at most a few times during debugging.

In general, don't use consult/1 and friends for external storage
of terms.  Simply use read and write for this.  Reading a file is
easy:

read_file(File) :-
	open(File, read, Fd),
	read(Fd, Term),
	read_file(Term, Fd),
	close(Fd).

read_file(end_of_file, _) :- !.
read_file(Term, Fd) :-
	assert(Term),
	read(Fd, Term2),
	read_file(Term2, Fd).

This way you avoid loosing dynamic declarations, the overhead
of source-administration, macro-expansion, style-checking, etc.

	Regards --- Jan

>:- dynamic
>  myfact/2.
>
>factfile('myfacts.pl').
>
>change(_, _) :-
>  factfile(FName), not(exists_file(FName)),
>  tell(FName), nl, told, fail.
>change(_, _) :-
>  factfile(FName), consult(FName), fail.
>change(X, Y) :-
>  factfile(FName), retractall(myfact(X, _)), assert(myfact(X, Y)),
>  tell(FName), listing(myfact), told.
>
>go :-
>  between(1,300,X), between(1,300,Y),
>  change(Y, X),
>  garbage_collect,
>  statistics(heapused, HU),
>  writef("Heap Used: %w(%w)\n", [HU]), fail.
>go.