lua-users home
lua-l archive

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


On Mon, Nov 9, 2020 at 6:29 PM Ranier Vilela <> wrote:
> Realloc only is secure like this:
>   (void)ud; (void)osize;  /* not used */
>   if (nsize == 0) {
>     free(ptr);
>     return NULL;
>   }
>   else
>   {
> void * newptr;
> newptr = realloc(ptr, nsize);
> if (newptr == NULL)
> return ptr;
> return newptr;
>   }

That is plain wrong for l_alloc function. Look at the docs. It says
you must behave like realloc, and you are not doing it. These is the
least of your problems.

In your implementation you are returning a valid pointer when realloc
fails. So if I call your function to grow a block, and it can not grow
it I will receive a valid ptr, then use it, write out of boundaries
and chaos ensues. And I've used several implementations of realloc on
which it can grow the block without copying it ( typical cases are
when allocator internally rounds up block for certain size ranges and
when you use something similar to sbrk and grow the top allocated
block ).

In fact this function of yours is plain wrong. If you assume you can
detect failure by testing the returned pointer ( which is not allways
true ) you still have to keep a copy outside for that test, so just
use realloc.

OTOH, the bundled l_alloc which behaves like realloc is perfectly
safe, as plain realloc is. Everybody (which wants to recover from
allocation failures, the ones not wanting to bother use abort on error
wrapper, like the classic xmalloc/xrealloc many libs provide ) knows
than when you call realloc you have to keep a copy of the ptr if you
do not want to loose track on allocation failures. l_alloc does NOT
want to recover from allocation failures, it's just a convenience
wrapper for realloc. The callers of the l_alloc do, and are the ones
any knowledgeable C programmer would look at to hunt for memory leaks,
just from the description of the interface in the manual.

Francisco Olarte.