LuaJIT FFI:程序终止时出现分段错误

我在 LuaJIT ffi 中尝试了一个非常简单的事情。 尝试在 C 代码中打开文件,然后关闭文件。

以下是 C 代码 fileWrite.c

#include<stdio.h>
#include<string.h>

FILE * createFile(char *fname){
    strcat(fname,".bin");
    FILE *file = fopen(fname, "wb");
    return file;
}

void close(FILE *fp){
    int status = fclose(fp);
}

在 lua 中使用 ffi 调用如下

local ffi = require("ffi")
local so_file_path_name = "./fileWrite.so" --path for .so file
local qCLib  = ffi.load(so_file_path_name)

local binfilepath = "./"

ffi.cdef[[
  void *malloc(size_t size);
  void free(void *ptr);

  typedef struct FILE FILE;
  FILE* createFile(char *fname);
  void close(FILE *fp);
  ]]

function create(fileName)
  filepath = binfilepath..fileName
  local filePathArg = ffi.new("char [?]", #filepath, filepath)
  local fp = qCLib["createFile"](filePathArg);
  return fp;
end

function close(fp)
    qCLib["close"](fp)
    fp = nil
end

file = create("test")
print(file)
close(file)
print("关闭后")

但是当我运行代码时,出现分段错误 :

$ luajit test.lua
cdata<struct FILE *>: 0x01dc9610
after closing
Segmentation fault (core dumped)

我在 ubuntu 14.04 上使用 luajit 版本 LuaJIT 2.0.4

任何有关如何调试此分段错误的提示将非常有帮助

点赞