Calculating bytes in heap free?
SRLM
Posts: 5,045
I'm trying to figure out how much memory is available for new/malloc use, but I must be missing something.
No matter what number I start "available" at, this function always spits out an address (such as 0x00006C48) and the original "available" amount after a single iteration of the loop.
Does anybody have any better suggestions on how to measure heap space?
I'm trying to parse malloc.c from here: https://code.google.com/p/propgcc/source/browse/lib/stdlib/malloc.c
Side note: I'm compiling in C++, but I'm using the new/delete from the TightMemory wiki page (c++-alloc.h).
void FreeMemoryTest(){ unsigned int available = 1000000; void * block = NULL; for(;available > 0; available--){ block = (void *) malloc(sizeof(char)*available); if(block != NULL){ debug->Put("\r\nFound match! Address: "); debug->Put(Numbers::Hex(block, 8)); free(block); break; } } debug->Put("\r\nFree Store memory available: "); debug->Put(Numbers::Dec(available)); }
No matter what number I start "available" at, this function always spits out an address (such as 0x00006C48) and the original "available" amount after a single iteration of the loop.
Does anybody have any better suggestions on how to measure heap space?
I'm trying to parse malloc.c from here: https://code.google.com/p/propgcc/source/browse/lib/stdlib/malloc.c
Side note: I'm compiling in C++, but I'm using the new/delete from the TightMemory wiki page (c++-alloc.h).
Comments
malloc() initially tries to get memory from its pool. If that fails, it calls sbrk() to add more memory to the pool. sbrk() unfortunately has no error checking, as the FIXME at the top of it says. The original plan was to check the current stack address and only allow allocation up to that (that's what the MIN_STACK define and the commented out "here" variable were for). That fails for threads other than the original one, though, so it was removed. The down side is that there's no error checking at all.
A reasonable compromise would be to refuse to allocate past the end of HUB memory -- that at least would add some sanity checking, although it still could over-allocate into the stack space.
Eric
I guess it's a bit of a thorny problem, with all the different uses of the Propeller memory. But isn't the current implementation broken, since it will (if I read it right) never not allocate memory, even if there is nothing free?
I'll check in a version that sets a "heap_end" variable from the stack on the first allocation by a thread whose stack is above the heap, and fails if allocation would go past heap_end. This should work in almost all cases to set a reasonable heap end. If no heap_end can be set (the main thread never mallocs, and the subsequent threads have statically allocated stacks but do malloc) then it'll fall back to behaving like now -- if heap_end isn't set then the allocation will always succeed.
Thanks for bringing this up!