Fix bad free when limit exceeded.

If the android limit code is enabled and a realloc would cross the
limit, the old code would free the original pointer. However, this
is invalid and the original pointer should not be changed.

No longer free the pointer in this case and add a test for this
case.

Bug: 501541998
hashtag:b/501541998

Test: All unit tests pass.
Test: Verify that reverting back to old behavior, new test fails.
(cherry picked from commit d00918bfbbe06d4a0841d52aabe6dea3a2432787)
Cherrypick-From: https://googleplex-android-review.googlesource.com/q/commit:a9fbca02c8fb86308957615e9bfda60c2465bd64
Merged-In: I52ccd62f4f513aa55989fb7dda816d13e3171120
Change-Id: I52ccd62f4f513aa55989fb7dda816d13e3171120
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 db814dc..3754db6 100644
--- a/tests/malloc_test.cpp
+++ b/tests/malloc_test.cpp
@@ -1291,8 +1291,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