lua-users home
lua-l archive

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


> 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