尝试读取json文件时出现分段错误

时间:2018-11-12 04:57:58

标签: c json linux ubuntu jsmn

我正在尝试使用jsmn解析json文件,但是在运行应用程序时出现分段错误。我正在使用C并在Ubuntu机器上进行编译。

请在下面找到代码段:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "jsmn.h"

#define JSON_FILE_PATH "/home/admin/Desktop/test/server/dataFile.json"
#define BUFFER_SIZE 5000
#define MAX_TOKEN_COUNT 128

// Read files
void readfile(char* filepath, char* fileContent)
{
    FILE *f;
    char c;
    int index;
    f = fopen(filepath, "r");
    ***while((c = fgetc(f)) != EOF){***     ------> seg fault
        fileContent[index] = c;
        index++;
    }
    fileContent[index] = '\0';
}

// This is where the magic happens
int parseJSON(char *filepath, void callback(char *, char*)){

    char JSON_STRING[BUFFER_SIZE];

    char value[1024];
    char key[1024];

    readfile(filepath, JSON_STRING);

   int i;
   int r;

   jsmn_parser p;
   jsmntok_t t[MAX_TOKEN_COUNT];

   jsmn_init(&p);

   r = jsmn_parse(&p, JSON_STRING, strlen(JSON_STRING), t, sizeof(t)/(sizeof(t[0])));

   if (r < 0) {
       printf("Failed to parse JSON: %d\n", r);
       return 1;
   }

   /* Assume the top-level element is an object */
   if (r < 1 || t[0].type != JSMN_OBJECT) {
       printf("Object expected\n");
       return 1;
   }

   for (i = 1; i < r; i++){

       jsmntok_t json_value = t[i+1];
       jsmntok_t json_key = t[i];


       int string_length = json_value.end - json_value.start;
       int key_length = json_key.end - json_key.start;

       int idx;

       for (idx = 0; idx < string_length; idx++){
           value[idx] = JSON_STRING[json_value.start + idx ];
       }

       for (idx = 0; idx < key_length; idx++){
           key[idx] = JSON_STRING[json_key.start + idx];
       }

       value[string_length] = '\0';
       key[key_length] = '\0';

       callback(key, value);

       i++;
   }

   return 0;
}

// Only prints the key and value
void mycallback(char *key, char* value){
    printf("%s : %s\n", key, value);
}

int main()
{
    parseJSON(JSON_FILE_PATH, mycallback);
    return 0;
}

读取文件的操作完成后,在显示的行之后出现分段错误。

在调试时,此时f包含0x00值,这意味着它无法识别文件。

为什么文件在该位置存在可能会发生这种情况?

我尝试更改路径,但仍然存在相同的问题。

1 个答案:

答案 0 :(得分:0)

找到解决方案:

索引在使用前未初始化 char c应该是int c-fgetc返回一个int

相关问题