【发布时间】:2017-11-02 10:55:59
【问题描述】:
我在将 Lua 字符串转换为 C 字符数组时遇到了一个奇怪的问题。
local str = "1234567890abcdef"
local ffi = require "ffi"
ffi.cdef[[
int printf(const char *fmt, ...);
]]
print(#str)
print(str)
local cstr = ffi.new("unsigned char[?]", #str, str)
运行此代码获取:
[root@origin ~]# luajit test.lua
16
1234567890abcdef
Segmentation fault
我知道ffi.new("unsigned char[?]", #str+1, str) 会解决这个问题,但我不知道为什么。
我认为这不是\0 的问题,因为我发现了一些奇怪的地方。
- 如果
str不是 16 字节,则不会发生这种情况。 - 如果我删除了我没有使用的
ffi.cdef,就不会发生这种情况。 -
如果我把
ffi.cdef放在ffi.new后面,就不会发生这种情况。[root@origin ~]# luajit test.lua 17 1234567890abcdefg // this is the result that I only append a 'g' to `str`.
我尝试使用默认编译器参数的 Luajit 2.0.5 和 Luajit 2.1.0-beta3。
那么,有谁知道这是怎么回事,谢谢。
【问题讨论】:
-
这个问题是由于缺少终止零的地方。您必须使用
#str+1。 -
@EgorSkriptunoff 我不这么认为,你能解释一下为什么它只发生在转换 16 字节字符串时?