1

我的代码如下:

local ffi = require "ffi"
local ffi_C = ffi.C
local ffi_typeof = ffi.typeof
local ffi_new = ffi.new
local ffi_string = ffi.string
local NULL = ngx.null
local tostring = tostring

ffi.cdef[[
    char * strtok(char * str, const char * delimiters);
]]

local p_char_type = ffi_typeof("char[?]")

function split(src, c)
    local result = {}

    local pch = ffi_new(p_char_type, 1)
    local psrc = ffi_new(p_char_type, #src)
    local pc = ffi_new(p_char_type, #c)

    ffi.copy(psrc, src)
    ffi.copy(pc, c)
    pch = ffi_C.strtok(psrc, pc)

    while pch do
        table.insert(result, ffi_string(pch))
        pch = ffi_C.strtok(NULL, pc)
        ngx.log(ngx.ERR, "pch ok")
    end

    ngx.log(ngx.ERR, "split ok")

    return result
end

当我运行我的 nginx 时,发生了一些错误!由while循环返回后,nginx工作进程崩溃,信号11。最后一个ngx.log无法运行。我该如何处理?

4

1 回答 1

1
local psrc = ffi_new(p_char_type, #src)
ffi.copy(psrc, src)

ffi.copy当给定一个字符串源时,也会复制一个空终止符,但是您的数组太小而无法容纳它,从而导致溢出。

此外,strtok考虑使用 Lua 模式,而不是使用 。它们更安全、更易于使用,并且不依赖于 FFI。

于 2014-06-04T17:57:42.373 回答