Shop OBEX P1 Docs P2 Docs Learn Events
Determining free memory — Parallax Forums

Determining free memory

DavidZemonDavidZemon Posts: 2,973
edited 2014-11-09 08:57 in Propeller 1
Dave Hein got me thinking about how to do this in this thread. Some google searches and basic understanding of the stack/heap space makes me think there is no good way to truly determine the total number of free bytes (plus it would be very useful by itself, without knowing the fragmentation). So I've settled on something that I think would be perfectly acceptable for 90% of cases implemented on the Propeller: a function that finds the single largest contiguous free block to a specified precision. I'd love for others to jump in and provide their opinions on and/or code for determining free memory.

But I have an issue with my function... I'm getting odd results. I have the following simple loop:
void *ptr = malloc(128);
start = CNT;
bytes = get_largest_free_block_size();
len = CNT - start;
printf("Largest free block: %05d; Runtime: %03d us" CRLF, bytes, len / MICROSECOND);

and I eventually get the following output:
Largest free block: 06048; Runtime: 298 us
Largest free block: 05888; Runtime: 297 us
Largest free block: 05760; Runtime: 297 us
Largest free block: 05696; Runtime: 307 us
Largest free block: 05696; Runtime: 318 us
Largest free block: 05696; Runtime: 318 us
Largest free block: 05696; Runtime: 318 us
Largest free block: 05696; Runtime: 322 us
Largest free block: 05696; Runtime: 322 us

It continues on printing 5696, seemingly forever.

Here's the function:
size_t get_largest_free_block_size (const uint8_t precision = 32) {
    size_t        largestSuccess  = 0;
    size_t        smallestFailure = 32*1024;
    size_t        nextAttempt     = 32*1024;

    uint8_t *ptr = NULL;

    do {
        ptr = (uint8_t *) malloc(nextAttempt);

        // If the allocation succeeded, free the memory as quickly as
        // possible
        if (NULL != ptr) {
            free(ptr);
            largestSuccess = nextAttempt;
        } else
            // If the allocation fails, try the next smallest
            smallestFailure = nextAttempt;


        nextAttempt = (smallestFailure - largestSuccess) / 2 +
                largestSuccess;
    } while (precision < (smallestFailure - largestSuccess));

    return largestSuccess;
}

Anyone know what's going on?

Comments

Sign In or Register to comment.