lua-users home
lua-l archive

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


On Sat, 1 Apr 2023 at 14:04, Michael L. <michael.lix12@gmail.com> wrote:
>
> Hello everyone,
>
> I am using lua 5.4 to run a larger project. I have my own realloc /
> malloc / free implementation. Initially, I thought I would print a
> warning when lua would make a realloc equivalent to free(NULL). I
> thought this should never happen because it is useless to do this.
> When running the code the warning was printed all the time. I was not
> able to track down when exactly this happens. Does somebody know why
> and when this occurs?

Your description is a bit confusing. a realloc equivalent to
free(NULL) is realloc(NULL, 0), but lua_alloc is documented as
behaving like free on nsize=0 and like realloc otherwise. I assume you
are getting ptr=NULL, nsize=0. Just do like the example and free ptr.

If your library prints a warning when free(NULL) is called, it is not
well done, free(NULL) is normal and even usual.


> 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?

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.
Before going to C++ I regularly used '#define xfree(p) do { free(p);
(p)=NULL; } while(0)', (which I know cannot be used if p has side
effects ) to deallocate pointers in the middle of functions, which
simplified the code. You init all your pointers with NULL, malloc or
realloc on them, xfree them if you need to free the mem early in the
function and free all off them at the end. It may waste a few cycles,
but makes coding easier.

So, free(NULL) is useless as you can do if(x) free(x), but free must
test anyway and the check clutters the code.

Francisco Olarte.