lua-users home
lua-l archive

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


On Sat, Apr 01, 2023 at 09:06:08PM -0400, Sean Conner wrote:
> It was thus said that the Great Francisco Olarte once stated:
> > On Sat, 1 Apr 2023 at 14:04, Michael L. <michael.lix12@gmail.com> wrote:
> > >
> > > It does not really matter for the code in the end. I can I would
> > > simply like to know this out of curiosity. These calls just seem
> > > unnecessary to me. The lua documentation even says that free(NULL)
> > > should has no effect, so why even call it?
> > 
> > Why not?
> 
>   Because the new C23 standard is looking to make realloc(x,0) **UNDEFINED
> BEHAVIOR**!  [1] In fact, C17 apparently make realloc(x,0) as free() as
> **OBSOLESCENT**!  (really big bold upper case etc. to drive the point
> across).  Beware of using Lua with C23 it seems.
> 
> > It is not just lua, in C free(NULL) is no-op, realloc(x,0) is
> > equivalent to free(x). This is useful to simplify error recoveries and
> > function exits.
> 
>   For now.

The Lua documentation explicitly requires of a lua_Alloc handler that, "When
nsize is zero, the allocator must behave like free and then return NULL."
Moreover, it gives an example implementation as,

  static void *l_alloc (void *ud, void *ptr, size_t osize,
                                             size_t nsize) {
    (void)ud;  (void)osize;  /* not used */
    if (nsize == 0) {
      free(ptr);
      return NULL;
    }
    else
      return realloc(ptr, nsize);
  }

So this is all well-defined in both existing C standards as well as the
forthcoming standard.

Re: free(NULL), it's both well-defined now and in the forthcoming standard;
and that will never change as it's an idiomatic coding pattern for the
reason mentioned earlier.