Re: [cc65] How to count free memory

Date view Thread view Subject view

From: Ullrich von Bassewitz (uz_at_musoftware.de)
Date: 2003-02-01 11:08:26


Hi!

On Sat, Feb 01, 2003 at 09:49:11AM +0100, Tim Schürmann wrote:
> Another stupid question about the memory:

There are stupid questions, but yours is definitely not one of them:-)

> In my program i'm doing some wild "malloc" and "free"-actions (please,
> don't ask why ;)). Now i want to show the user at runtime(!) how many
> memory (in byte) he could actually use.
>
> The best solution seems to be a C-Funktion, which will return the free
> bytes as an unsigned int.

The problem with this approach is that you can have kilobytes of memory free,
without having a single byte that can be used by the program. This happens
when the heap gets heavily fragmented. If there are several hundred blocks
with less than 32 bytes available, your program won't be able to allocate one
block with 32 byte, even if such a function returns free space.

Anyway, since such a function can be useful sometimes, here is an
implementation. I will add this and a few more heap utility functions to the
development version.

    #include "../libsrc/common/_heap.h"

    unsigned heapfree (void)
    {
        /* Walk the free list */
        unsigned Size = 0;
        register struct freeblock* F = _hfirst;
        while (F) {
            Size += F->size;
            F = F->next;
        }

        /* Add the big chunk at _hptr */
        Size += (_hend - _hptr) * sizeof (*_hend);

        /* Done */
        return Size;
    }

Please note that you need the _heap.h header file from the source distribution
to compile this code. And, since you're accessing implementation details, the
code may not work with future versions of the library. To avoid these
problems, I will add this and a few more heap utility functions to the
development version, so they should be in the next release.

Regards


        Uz


-- 
Ullrich von Bassewitz                                  uz_at_musoftware.de
----------------------------------------------------------------------
To unsubscribe from the list send mail to majordomo_at_musoftware.de with
the string "unsubscribe cc65" in the body(!) of the mail.


Date view Thread view Subject view

This archive was generated by hypermail 2.1.3 : 2003-02-01 11:09:01 CET