Re: [hackers] [st] Add xmalloc and xrealloc wrappers || "Roberto E. Vargas Caballero"

From: Roberto E. Vargas Caballero <>
Date: Fri, 14 Sep 2012 15:20:28 +0200

> > I don't see how those guidelines apply to xrealloc(). If realloc()
> > ever fails, the program exits, so there is no memory leak.
> The programming language does not define what happens before
> and after program execution. Modern OS may cleanup your memory
> on exit() older ones may not.

"The programming language" can define it, in this case ANSI C or POSIX don't
define it, but other language definition could define it (for C or for other
language). In this case xrealloc and xmalloc are only wrappers which
guaranteed that they return with a valid pointer. In case of error they call
die. They don't know anything about the other part of the program.

> >>> +void *
> >>> +xrealloc(void *p, size_t len) {
> >>> + if((p = realloc(p, len)) == NULL)
> >>> + die("Out of memory");
> >>> + return p;
> >>> +}

As you can see xrealloc modifies the local variable p, so the caller
variable keeps its original value, so no memory leak is present. If you
aren't confortable with free'ed memory on exit, then put the correct atexit
functions and free the memory, you can do it because you have the original
pointers. But this is not a xmalloc/xrealloc issue.

> Always checking bounds before each (x)realloc call is better than doing it
> at on place?

xrealloc is only a wrapper of realloc, so it doesn't have any way of knowing
what limits should check, it is the same behaviour of realloc. Also,
xrealloc doesn't know what you have to do in a case of limit error (terminate
the program?, print something to the user?). The checking must be done in
other part where you know the context information (for example what limits
are you talking and what you/user want to do). It is exactly the same
problem that realloc itself has.

> The name xrealloc() suggests generic realloc() replacement not a
> 'works for row and col specific case' realloc().

Yeah, a generic realloc replacement, where you don't have enough information
about limits. In this case is safe for the caller don't check the limit
due to 'row and col specific case', but again this is not a xrealloc issue,
it is a xrealloc caller issue.

Best regards.
Received on Fri Sep 14 2012 - 15:20:28 CEST

This archive was generated by hypermail 2.3.0 : Fri Sep 14 2012 - 15:24:14 CEST