0

I am using json-c to parse json files in my project. I tried creating json_tokener_parse but this has resulted in seg-fault. could any please check and tell me the reason for segfault.

#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);
}
2
  • Have you written in a check that mmap returns a non-NULL pointer? Commented May 24, 2018 at 17:39
  • I tried adding that check, even after that, I still get seg fault. Commented May 25, 2018 at 7:08

1 Answer 1

1

json_tokener_parse() takes a null-terminated string. A text file is not null-terminated. You'll have to use json_tokener_parse_ex() and specify the length.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.