[comp.sys.atari.st] Malloc - what it really does

klute%trillian.irb@unido.uucp (Rainer Klute) (10/20/89)

In article <1322@engage.enet.dec.com> wallace@oldtmr.dec.com (Ray Wallace) writes:
>In article <111500042@uxa.cso.uiuc.edu>, glk01126@uxa.cso.uiuc.edu writes...
>>	1) Does Malloc(-1L) not work properly?
>This only returns the size of the largest chunk of free memory. So if you have
>holes in your free memory (non-contiguous) then it will return a number
>smaller than the total of all free memory.

From what I have found out Malloc (-1L) returns the *sum* of the
sizes of *all* free memory chunks. So, what you should not do
without further checking is as follows:

	buffer_size    = Malloc (-1L);
	buffer_address = Malloc (buffer_size);

This will not work as intended because the second Malloc will
result in a pointer to the largest available chunk only, not to
all the free memory, because the latter is not neccessarily
contingous! So the buffer located at 'buffer_address' does not
have a size of 'buffer_size' but of some smaller value. The
real buffer size you can estimate by adding another statement
to those above:

	real_buffer_size = buffer_size - Malloc (-1L);

Disclaimer: I still use TOS 1.0.

  Dipl.-Inform. Rainer Klute      klute@trillian.irb.informatik.uni-dortmund.de
  Univ. Dortmund, IRB             klute@unido.uucp, klute@unido.bitnet
  Postfach 500500         |)|/    ...uunet!mcvax!unido!klute
D-4600 Dortmund 50        |\|\    Tel.: +49 231 755-4663

apratt@atari.UUCP (Allan Pratt) (10/24/89)

klute%trillian.irb@unido.uucp (Rainer Klute) writes:

>wallace@oldtmr.dec.com (Ray Wallace) writes:
>From what I have found out Malloc (-1L) returns the *sum* of the
>sizes of *all* free memory chunks.

This is emphatically not the case, and never has been.

The original answer was right: it returns the size of the LARGEST
SINGLE CHUNK of free memory.  A common way to find out how much memory
there is in the system is to call Malloc(-1L) many times, each time
allocating a chunk of the size it returns, until it returns zero.
Then you report the answer and Mfree() all the chunks you allocated.

Of course, Malloc(-1) is evil if you're in a multi-tasking environment,
because in the time between the Malloc(-1) and actually allocating the
block of the size it reported, you could be preempted and somebody else
might allocate that block away from you!  This is only one of a whole
class of problems which a multitasking TOS would have to address: the
single-thread, global, I-own-the-machine nature of TOS applications.

============================================
Opinions expressed above do not necessarily	-- Allan Pratt, Atari Corp.
reflect those of Atari Corp. or anyone else.	  ...ames!atari!apratt