X-Git-Url: https://codewiz.org/gitweb?a=blobdiff_plain;f=bertos%2Fstruct%2Fheap.c;h=1e4d60530336c7ae0f86e8cf891e7eeb44ccf63a;hb=f884c67ed85598875ef683987323fd6085e01e14;hp=27f8032567ae8945d70e6482a31a2c0afd90db85;hpb=c81265e6459403444c859758db53a9675c3a4ec7;p=bertos.git diff --git a/bertos/struct/heap.c b/bertos/struct/heap.c index 27f80325..1e4d6053 100644 --- a/bertos/struct/heap.c +++ b/bertos/struct/heap.c @@ -56,7 +56,7 @@ void heap_init(struct Heap* h, void* memory, size_t size) memset(memory, FREE_FILL_CODE, size); #endif - ASSERT2((((uintptr_t)memory % sizeof(heap_buf_t)) == 0), + ASSERT2(((size_t)memory % alignof(heap_buf_t)) == 0, "memory buffer is unaligned, please use the HEAP_DEFINE_BUF() macro to declare heap buffers!\n"); /* Initialize heap with a single big chunk */ @@ -127,9 +127,9 @@ void heap_freemem(struct Heap* h, void *mem, size_t size) if (!size) size = sizeof(MemChunk); - /* Special case: first chunk in the free list */ + /* Special cases: first chunk in the free list or memory completely full */ ASSERT((uint8_t*)mem != (uint8_t*)h->FreeList); - if (((uint8_t *)mem) < ((uint8_t *)h->FreeList)) + if (((uint8_t *)mem) < ((uint8_t *)h->FreeList) || !h->FreeList) { /* Insert memory block before the current free list head */ prev = (MemChunk *)mem; @@ -184,6 +184,25 @@ void heap_freemem(struct Heap* h, void *mem, size_t size) } } +/** + * Returns the number of free bytes in a heap. + * \param h the heap to check. + * + * \note The returned value is the sum of all free memory regions + * in the heap. + * Those regions are likely to be *not* contiguous, + * so a successive allocation may fail even if the + * requested amount of memory is lower than the current free space. + */ +size_t heap_freeSpace(struct Heap *h) +{ + size_t free_mem = 0; + for (MemChunck *chunk = h->FreeList; hunk; chunk = chunk->next) + free_mem += chunck->size; + + return free_mem; +} + #if CONFIG_HEAP_MALLOC void *heap_malloc(struct Heap* h, size_t size)