lua-users home
lua-l archive

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

>>>>> "Roberto" == Roberto Ierusalimschy <> writes:

 Roberto> I would like to see that demonstration.

Running this with a small memory ulimit, using jemalloc, shows that
realloc can fail to shrink (you might have to play around with the
sizes, I guess, but these worked for me):

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv)
    char buf[512];
    void *block1 = malloc(2048);
    void *block2;
    void *volatile ptr;

    while ((ptr = malloc(2048)))

    block2 = realloc(block1, 1024);
    sprintf(buf, "block1 = %p block2 = %p\n", block1, block2);
    write(2, buf, strlen(buf));
    return 0;

% (ulimit -v 32768; ./a.out)   # tested on freebsd
block1 = 0x800e16000 block2 = 0x0

tcmalloc also has this issue; I _believe_ that the default glibc malloc
does not (but I don't use linux and haven't tested it). It is obvious
when you consider that many allocators use the strategy of allocating
slabs of fixed-size chunks; in such cases chunks can't be arbitrarily
split, so realloc to a smaller size has to copy if it's to free up any
space at all.

 Roberto> About the standard, that depends on your interpretation.

No. The standards do not require that realloc not fail when shrinking a
block. (They would have said so in that case.) They _do_ require that
failure leaves the original block untouched.