diff --git a/lib/libc/stdlib/malloc/mrs/mrs.c b/lib/libc/stdlib/malloc/mrs/mrs.c index f54807c54fbf..ccc5ad3f500a 100644 --- a/lib/libc/stdlib/malloc/mrs/mrs.c +++ b/lib/libc/stdlib/malloc/mrs/mrs.c @@ -1515,6 +1515,19 @@ mrs_realloc(void *ptr, size_t size) mrs_debug_printf("mrs_realloc: called ptr %p ptr size %zu new size %zu\n", ptr, old_size, size); + /* + * Just return the pointer if our desired size fits. + * + * Only try to reclaim space by copying if we'd recover at least + * half of the allocated storage. In any other case we can't + * tell the difference between shrinking and linear growth into + * a very large over allocation (e.g., growing into snmalloc's + * power-of-two buckets by 1K). + */ + if (ptr != NULL && cheri_gettag(ptr) && cheri_getoffset(ptr) == 0 && + size <= old_size && old_size - size > (old_size >> 1)) + return (ptr); + void *new_alloc = mrs_malloc(size); /*