lua-users home
lua-l archive

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


Thank you for your reply.

I think it's a solution, but I still have a question.

>void *newptr = realloc(ptr, nsize);
>   if (newptr == NULL && ptr != NULL && nsize <= osize)
>      return ptr;  /* keep the original block */

If it runs into such code path.
Which value would you pass to the l_alloc function when invoking it
next time,  nsize or osize(i.e. nsize <= osize)?
You don't exactly know whether the expression (i.e. newptr == NULL &&
ptr != NULL && nsize <= osize) is true or not (when this function was
called last time).

Best Regards.
Sunshilong

On Mon, Aug 10, 2020 at 10:53 PM Roberto Ierusalimschy
<roberto@inf.puc-rio.br> wrote:
>
> > I want to use a self-defined memory acquirement function instead of
> > using realloc(3) in the l_alloc function.
> > Since I am a newbie, I don't know if there are some potential problems.
> > Could somebody shed some light on this problem?
>
> All you need to know is documented here:
>
>   https://www.lua.org/manual/5.3/manual.html#lua_Alloc
>
> As long as you meet those requirements, everything should be fine.
>
> As already pointed out and documented in the above link, Lua assumes
> that its l_alloc function cannot fail when shrinking a block. If your
> collector does not assure it, it is trivial to change l_alloc so that it
> returns the original block when a shrinking would fail:
>
> 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 {
>     void *newptr = realloc(ptr, nsize);
>     if (newptr == NULL && ptr != NULL && nsize <= osize)
>       return ptr;  /* keep the original block */
>     else
>       return newptr;
>   }
> }
>
> -- Roberto