Re: luajit string to char * conversion

  • From: Alex <initrd.gz@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Wed, 26 Nov 2014 10:28:19 -0500

No. `v` is allocated by LuaJIT and is garbage collected; you do not call
free on it. (also the `if v` is always true; LuaJIT will throw an error if
it can't allocate it).

On Wed, Nov 26, 2014 at 10:20 AM, marcelo nicolet <marcelo.nicolet@xxxxxxxxx
> wrote:

>  So, if I use (as an example)
>
> local bufsize = 128
> local v = ffi.new( "char[?]", bufsize )
>
> if ( v ) then
>     C.recv( fd, v, bufsize, 0 )
>     -- do something with v content
>     C.free( v )
> end
>
> Is this code ok?
>
>
> On 11/22/2014 07:44 PM, Florian Weimer wrote:
>
> * marcelo nicolet:
>
>
>  I catched the trick: when the argument will not be modified, declaring
> it const does the job.
> But when it will be modified (as in my example for recv() ) to have in
> the middle of lua code a call to malloc() and then to free() is not a
> "good thing" to my taste.
>
>  At least it's explicit about the lifetime of the temporary copy, and
> it doesn't drive the garbage collector forward.
>
>
>  What about
> local v = ffi.new( "char[?]", bufsize )
> Is it ok?
> TIA
>
>  Yes, but you still have to copy the string, and make sure that you
> deal with the terminating NUL byte.
>
>
>  PS: what if malloc() cannot allocate any memory? NULL from malloc
> comes as nil to lua code?
>
>  Correct (if malloc does indeed return NULL—usually, the kernel kills
> entire processes if it runs out of memory).
>
>
>
>
>


-- 
Sincerely,
Alex Parrill

Other related posts: