correct • elegant • free

△ Comp.lang.c △

◅ Book Suggestion

Book Suggestion ▻

Memory reallocators

In article <>,
Richard Bos <> wrote (quoting me):
>> I've recently come to the distressing conclusion that C is the wrong
>> language in which to write a memory reallocator.
>Out of curiosity, can you explain that?

Sure.  Perhaps a better way to say it would be that either interface can
easily be called wrongly.

With the standard realloc() interface,

    void *realloc(void *, size_t);

it's tempting to write code like this.

    x = realloc(x, n);
    if (!x) {
        ... deal with error

But in the event of an allocation failure, you've just lost your buffer
and created a memory leak.  This might be acceptable if you're going to
call exit() as soon as there's an allocation failure (which is actually
a reasonable strategy for many small programs).  But if you need to
clean up, or attempt any sort of recovery, you need to write this.

    y = realloc(x, n);
    if (y)
        x = y;
    else {
        ... deal with error: x still points to original buffer

Similarly, with the interface proposed by Steve Maguire,

    int resize_memory(void **, size_t);

it's easy to write this.

    if (!resize_memory(&x, n)) {
        ... deal with error

This should elicit a warning from your compiler: adding a cast will
likely shut up the compiler, but not actually fix the code.  You can't
use `void **' as a generic pointer-to-pointer, although you can get away
with it on most common architectures.  To make this code right, you need
to introduce a real object with type `void *' somewhere.

    void *v;

    v = x;
    if (!resize_memory(&v, n)) {
        ... deal with error
    x = v;

Tim Goodwin   | "If you don't know what closures are, you probably don't
Leicester, UK | want to know what closures are." -- Larry Wall

Original headers:

From: (Tim Goodwin)
Newsgroups: comp.lang.c
Subject: Memory reallocators (was Re: Book Suggestion)
Date: 25 Feb 2000 10:53:01 -0000
Message-ID: <895mv3$2t4$>
References: <88nins$j6l$>
  <> <893ken$1gm$>

△ Comp.lang.c △

◅ Book Suggestion

Book Suggestion ▻