diff --git a/os/mm/mm_heap/mm_get_heapindex.c b/os/mm/mm_heap/mm_get_heapindex.c index 446a179195..2de2d55754 100644 --- a/os/mm/mm_heap/mm_get_heapindex.c +++ b/os/mm/mm_heap/mm_get_heapindex.c @@ -37,6 +37,9 @@ extern struct mm_heap_s g_mmheap[CONFIG_MM_NHEAPS]; int mm_get_heapindex(void *mem) { int heap_idx; + if (mem == NULL) { + return 0; + } for (heap_idx = 0; heap_idx < CONFIG_MM_NHEAPS; heap_idx++) { if (mem < (void *)(g_mmheap[heap_idx].mm_heapstart + g_mmheap[heap_idx].mm_heapsize) && mem >= (void *)g_mmheap[heap_idx].mm_heapstart) { return heap_idx; diff --git a/os/mm/umm_heap/umm_realloc.c b/os/mm/umm_heap/umm_realloc.c index d9d2a340e2..8117d996cf 100644 --- a/os/mm/umm_heap/umm_realloc.c +++ b/os/mm/umm_heap/umm_realloc.c @@ -116,11 +116,15 @@ void *realloc_at(int heap_index, void *oldmem, size_t size) FAR void *realloc(FAR void *oldmem, size_t size) { int heap_idx; + int prev_heap_idx; void *ret; #ifdef CONFIG_DEBUG_MM_HEAPINFO ARCH_GET_RET_ADDRESS #endif heap_idx = mm_get_heapindex(oldmem); + if (heap_idx < 0) { + return NULL; + } #ifdef CONFIG_DEBUG_MM_HEAPINFO ret = mm_realloc(&g_mmheap[heap_idx], oldmem, size, retaddr); #else @@ -131,6 +135,7 @@ FAR void *realloc(FAR void *oldmem, size_t size) } /* Try to mm_malloc to another heap */ mdbg("After realloc, memory can be allocated to another heap which is not as same as previous.\n"); + prev_heap_idx = heap_idx; for (heap_idx = 0; heap_idx < CONFIG_MM_NHEAPS; heap_idx++) { #ifdef CONFIG_DEBUG_MM_HEAPINFO ret = mm_malloc(&g_mmheap[heap_idx], size, retaddr); @@ -138,6 +143,7 @@ FAR void *realloc(FAR void *oldmem, size_t size) ret = mm_malloc(&g_mmheap[heap_idx], size); #endif if (ret != NULL) { + mm_free(&g_mmheap[prev_heap_idx], oldmem); return ret; } }