Merge cherrypicks of ['googleplex-android-review.googlesource.com/40039025'] into 24Q3-platform-release.

Change-Id: Id0f8e2fb92ae094439b7b5052bc512c15d2b8bf9
diff --git a/libc/bionic/malloc_limit.cpp b/libc/bionic/malloc_limit.cpp
index 5128a35..e00b8c6 100644
--- a/libc/bionic/malloc_limit.cpp
+++ b/libc/bionic/malloc_limit.cpp
@@ -200,8 +200,7 @@
   if (bytes > old_usable_size && !CheckLimit(bytes - old_usable_size)) {
     warning_log("malloc_limit: realloc(%p, %zu) exceeds limit %" PRId64, old_mem, bytes,
                 gAllocLimit);
-    // Free the old pointer.
-    LimitFree(old_mem);
+    // Do not free the old pointer, it's still valid.
     return nullptr;
   }
 
diff --git a/tests/malloc_test.cpp b/tests/malloc_test.cpp
index a5916d3..88fc813 100644
--- a/tests/malloc_test.cpp
+++ b/tests/malloc_test.cpp
@@ -1289,8 +1289,10 @@
   memory = realloc(memory, 80 * 1024 * 1024);
   ASSERT_TRUE(memory != nullptr);
   // Now push past limit.
-  memory = realloc(memory, 130 * 1024 * 1024);
-  ASSERT_TRUE(memory == nullptr);
+  void* new_memory = realloc(memory, 130 * 1024 * 1024);
+  ASSERT_TRUE(new_memory == nullptr);
+  // The original pointer should still be valid, so free it.
+  free(memory);
 
   VerifyMaxPointers(max_pointers);
 #else