]> granicus.if.org Git - esp-idf/commitdiff
Merge branch 'bugfix/malloc_failure' into 'master'
authorIvan Grokhotkov <ivan@espressif.com>
Thu, 19 Oct 2017 13:30:26 +0000 (21:30 +0800)
committerIvan Grokhotkov <ivan@espressif.com>
Thu, 19 Oct 2017 13:30:26 +0000 (21:30 +0800)
heap: Fix race condition causing malloc() to fail under some conditions

See merge request !1424

1  2 
components/heap/multi_heap.c

index 98aa425015699226650a6c82c8b420ae6d64961f,cc621c0d88b13a580e8a1eaa78e13dc8fe19dc6b..93ae0c5f6761440458e149722bb199bd4db5ebcd
@@@ -351,8 -341,18 +351,18 @@@ void *multi_heap_malloc_impl(multi_heap
          return NULL;
      }
  
 -    MULTI_HEAP_LOCK(heap->lock);
 +    multi_heap_internal_lock(heap);
  
+     /* Note: this check must be done while holding the lock as both
+        malloc & realloc may temporarily shrink the free_bytes value
+        before they split a large block. This can result in false negatives,
+        especially if the heap is unfragmented.
+     */
+     if (heap->free_bytes < size) {
+         MULTI_HEAP_UNLOCK(heap->lock);
+         return NULL;
+     }
      /* Find best free block to perform the allocation in */
      prev = &heap->first_block;
      for (heap_block_t *b = heap->first_block.next_free; b != NULL; b = b->next_free) {