[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Bug#812403: libc6: remalloc(x, malloc_usage_size(x)) should not cause x to change.



Package: libc6
Severity: normal
Tags: upstream

Dear Maintainer,

I believe that realloc(x, malloc_usage_size(x)) should possibly extend
the size of the allocation of x, but not move it in memory.  glibc
appears to return a new block of memory for this idiom when the block is
already "large", presumably when it has changed to the mmap() allocator.
This idiom is potentially useful when doing things like allocating a
buffer that is "big enough" (might as well use the malloc overhead for
useful work, rather than wasting it).

Demonstration program:
#include <malloc.h>

int main(int argc, char *argv[])
{
    for(size_t i = 2; i < 100000000; i = i + (i>>1)) {
        void *x = malloc(i);
        size_t s = malloc_usable_size(x);
        printf("malloc(%zd)=%p malloc_usable_size(%p)=%zd (%zd spare) ",
                i, x, x, s, s - i);
        void *y = realloc(x, s);
        printf("realloc(%p, %zd)=%p %s\n", x, s, y,
                x == y ? "(ok)" : "(not ok)");
        free(y);
    }
}

Expected result: "(ok)" at the end of each line.
Actual result: "(not ok)" on all of the larger lines.

-- System Information:
Debian Release: stretch/sid
  APT prefers unstable
  APT policy: (500, 'unstable'), (1, 'experimental')
Architecture: amd64 (x86_64)
Foreign Architectures: i386

Kernel: Linux 3.16.0-4-amd64 (SMP w/4 CPU cores)
Locale: LANG=en_GB.UTF-8, LC_CTYPE=en_GB.UTF-8 (charmap=UTF-8)
Shell: /bin/sh linked to /bin/dash
Init: systemd (via /run/systemd/system)


Reply to: