lua-users home
lua-l archive

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

It was thus said that the Great Dirk Laurie once stated:
> I'm writing a binding for a C library with several kinds of structures
> that are allocated thus:
>     mystruct* M=alloc(mystruct);
> where alloc is a macro
>     #define alloc(obj) (obj*)calloc(1,sizeof(obj))
> Back in my youth we were told not to do that when the application, as
> this one does, only frees the structures right at the end.  Instead we
> were supposed to allocate a memory heap, reallocate it to double size
> when it gets exhausted, and write a function `alloc` that simply
> serves up bits off that heap.

  That's actually bad advice, as realloc() can move the memory block, thus
potentially rendering any existing pointers into the "heap" invalid.  Also,
in Standard C (C89 or C99) you don't need to cast the results from malloc(),
realloc() or calloc() (void * can be cast to any type of pointer by the

> I've been out of C for, oh, twelve years I suppose, and it occurs to
> me that in the meantime the algorithm behind `calloc` might have
> become clever enough to do just that, one heap per process.

  Even twelve years ago, I would advise to use the existing
malloc()/realloc()/calloc() on your system, unless you can prove that the
performance of the standard calls is not sufficient enough (or it's too
buggy) *on your target platform* to warrant a customized memory allocator. 
Even Lua, by default, will use the standard C calls.

> In a Lua binding there is the added possibility of allocating the
> required memory via lua_newuserdata.
> What do you think?

  It depends upon how the resulting objects are used.  So far, for all my
projects with Lua (some of which involve load testing), I've used
lua_newuserdata() and let Lua track the memory for me, and performance has
not really been an issue.  You could allocate the objects yourself and pass
it to Lua as a lightuserdata object, but it *really* depends on how the
object is used (so far, in about 45,000 lines of code (a mixture of C and
Lua, both work and personal projects) I think I've use a lightuserdata once.