0

我正在使用 json-c 来解析项目中的 json 文件。我尝试创建 json_tokener_parse 但这导致了段错误。任何人都可以检查并告诉我段错误的原因。

#include <sys/mman.h> 
#include <sys/stat.h>
#include <fcntl.h> // O_RDONLY
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<json-c/json.h>

int main() {
    int oflag = O_RDONLY;
    const char *path = "file.json";
    const int fd = open(path, oflag);

    // use stat to find the file size
    struct stat stat;
    int ret = fstat(fd, &stat);

    int mflags = MAP_SHARED; // information about handling the mapped data
    int mprot = PROT_READ|PROT_WRITE; // access permissions to the data being mapped 
    size_t size = stat.st_size;
    void *addr = mmap(NULL, size, mprot, mflags, fd, 0);
    const char *file = (char *)addr;

    json_object * jobj = json_tokener_parse(addr);     
    //json_parse(jobj);
}
4

1 回答 1

1

json_tokener_parse()接受一个以 null 结尾的字符串。文本文件不是以空值结尾的。您必须使用json_tokener_parse_ex()并指定长度。

于 2018-05-25T15:46:06.387 回答