Bug 5071 - realloc(): do not remap() if same number of pages
Summary: realloc(): do not remap() if same number of pages
Status: RESOLVED FIXED
Alias: None
Product: glibc
Classification: Unclassified
Component: libc (show other bugs)
Version: 2.4
: P3 minor
Target Milestone: ---
Assignee: Ulrich Drepper
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2007-09-26 09:42 UTC by Tomash Brechko
Modified: 2014-07-04 07:27 UTC (History)
1 user (show)

See Also:
Host: i686-redhat-linux-gnu
Target: i686-redhat-linux-gnu
Build: i686-redhat-linux-gnu
Last reconfirmed:
fweimer: security-


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Tomash Brechko 2007-09-26 09:42:19 UTC
strace of the following program on Linux x86 (4096 bytes/page) shows that there
are lots of redundant calls to mremap() (old size and new size are equal).  The
bug is present in glibc up to and including 2.6.1 (bug report Version field
doesn't have 2.6).

#include <stdlib.h>

int
main()
{
  const size_t size = 256 * 1024 + 4050;
  void *p;
  int i;

  p = malloc(size);
  for (i = 0; i < 100; ++i)
    p = realloc(p, size + i);

  return 0;
}


The following patch fixes the problem (comment line is copied from the similar
check in _int_realloc()):

--- malloc/malloc.c-orig        2007-09-26 13:28:36.000000000 +0400
+++ malloc/malloc.c     2007-09-26 12:57:41.000000000 +0400
@@ -3503,6 +3503,10 @@ mremap_chunk(p, new_size) mchunkptr p; s
   /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
   new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask;

+  /* don't need to remap if still within same page */
+  if (size + offset == new_size)
+    return p;
+
   cp = (char *)mremap((char *)p - offset, size + offset, new_size,
                       MREMAP_MAYMOVE);
Comment 1 Ulrich Drepper 2007-10-02 03:52:43 UTC
Applied to cvs.