clearing entire memory

Conor P. Cahill cpcahil at virtech.uucp
Fri Dec 1 04:13:39 AEST 1989


In article <13367 at s.ms.uky.edu>, kminor at ms.uky.edu (Kevin R. Minor) writes:
> Here's my question.  Is there a way to free up the entire memory
> without having to deallocate each node?  If I can free the entire tree
> structure in one step, it will dramatically save in run-time.  Either way,
> I'd like to know for my paper.


It depends upon how you are allocating the space for the tree.

If you are using malloc() to allocate each node individually, then you cannot
free the entire list in a single operation.

If you use malloc() to allocate room for say 1000 of these entries and you
handle the distribution of the pointers yourself, you can free the big 
chunks as opposed to the individual pointers.  This could be done as 
follows:

	struct mydata { .... struct mydata * p;};

	static struct mydata 	* head;
	static struct mydata	* top;
	static struct mydata	* ptr;
	static int		  count;

	struct mydata * mymalloc()
	{
		if( count == 0 )
		{
			count = 1000;
			ptr = (cast..) malloc(count * sizeof(struct...)
			/* check for valid malloc return here */
			if( head == NULL )
			{
				head = ptr;
			}
			else
			{
				top->p = ptr;
			}
			top = ptr++;
			top->p = NULL;
			count--;
		}
		count--;
		return(ptr++);
	}

	myfree()
	{
		while(head != NULL)
		{
			p = head;
			head = head->p;
			free(p);
		}
		count = 0;
	}

	NOTE-> The above code is untested, uncompiled, etc.  So there are sure
		to be typos, and possibly real problems, but you should get 
		the idea.
		

And finally, if you don't use any code that may use malloc() (and remember,
lots of section 3 commands use malloced areas) you could  do the following:

	saveptr = sbrk(0);
	/* do all of your allocating and such stuff */
	brk(saveptr);

Note that the use of brk() will break any of the malloc() family of functions,
so this is only usable if you are doing your own allocating.
-- 
+-----------------------------------------------------------------------+
| Conor P. Cahill     uunet!virtech!cpcahil      	703-430-9247	!
| Virtual Technologies Inc.,    P. O. Box 876,   Sterling, VA 22170     |
+-----------------------------------------------------------------------+



More information about the Comp.lang.c mailing list