Skip to content

Commit b3f66e8

Browse files
committed
fix NULL dereference in realloc, see issue #1304 and #1312
1 parent f22e047 commit b3f66e8

1 file changed

Lines changed: 17 additions & 9 deletions

File tree

src/alloc.c

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -374,16 +374,24 @@ void* _mi_theap_realloc_zero(mi_theap_t* theap, void* p, size_t newsize, bool ze
374374
size = _mi_usable_size(p,page);
375375
if (usable_pre!=NULL) { *usable_pre = mi_page_usable_block_size(page); }
376376
}
377-
if mi_unlikely(newsize<=size && newsize>=(size/2) && newsize>0 // note: newsize must be > 0 or otherwise we return NULL for realloc(NULL,0)
378-
&& mi_page_heap(page)==_mi_theap_heap(theap)) // and within the same heap
379-
{
380-
mi_assert_internal(p!=NULL);
381-
// todo: do not track as the usable size is still the same in the free; adjust potential padding?
382-
// mi_track_resize(p,size,newsize)
383-
// if (newsize < size) { mi_track_mem_noaccess((uint8_t*)p + newsize, size - newsize); }
384-
if (usable_post!=NULL) { *usable_post = mi_page_usable_block_size(page); }
385-
return p; // reallocation still fits and not more than 50% waste
377+
// check if we can reuse the existing block
378+
if mi_unlikely(newsize<=size && newsize>=(size/2) && newsize>0) { // note: newsize must be > 0 or otherwise we return NULL for realloc(NULL,0)
379+
mi_assert_internal(page!=NULL); // note: page!=NULL (since if p==NULL, we have size=0 and size>=newsize>0
380+
#if MI_THEAP_INITASNULL
381+
if (theap!=NULL)
382+
#endif
383+
{
384+
if (mi_page_heap(page)==_mi_theap_heap(theap)) { // and within the same heap
385+
mi_assert_internal(p!=NULL);
386+
// todo: do not track as the usable size is still the same in the free; adjust potential padding?
387+
// mi_track_resize(p,size,newsize)
388+
// if (newsize < size) { mi_track_mem_noaccess((uint8_t*)p + newsize, size - newsize); }
389+
if (usable_post!=NULL) { *usable_post = mi_page_usable_block_size(page); }
390+
return p; // reallocation still fits and not more than 50% waste
391+
}
392+
}
386393
}
394+
// otherwise allocate a fresh block
387395
void* newp = mi_theap_umalloc(theap,newsize,usable_post);
388396
if mi_likely(newp != NULL) {
389397
if (zero && newsize > size) {

0 commit comments

Comments
 (0)