lua-users home
lua-l archive

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


Pierre Chapuis wrote:
> On 08.11.2011 11:30, Daurnimator wrote:
> >See http://luajit.org/ext_ffi_semantics.html#init
> >
> >Byte arrays may also be initialized with a Lua string. This copies
> >the
> >whole string plus a terminating zero-byte. The copy stops early only
> >if the array has a known, fixed size.
> >
> >
> >I guess a VLA (A variable-length array) is not of a known, fixed
> >size.
> >(though I guess it should be.....)

The size of a VLA is held in the created _instance_, but not in
the _type_ (actually that's the main idea behind a VLA). The VLA
type itself is of unknown size and that's what matters when
initializing an array with a string.

> My reasoning is: I'm using nelem
> (http://luajit.org/ext_ffi_api.html#ffi_new) to copy a string that
> represents raw bytes (and has no reason to be \0-terminated).
> It should behave approximately like strncpy().

No, it's really two steps in one, like malloc() + memcpy(). If you
don't want to create the space for the extra \0, simply use:

  local l = #str
  local s = ffi.new("char[?]", l)
  ffi.copy(s, str, l)
  -- Don't use ffi.copy(s, str), since that would copy the \0, too.

> But what I find the most strange is that the segfault doesn't happen
> at that line, it happens later when the memory is garbage collected.

The extra byte written beyond the end of the array trashes the
memory allocator info.

--Mike