gpt4 book ai didi

c - 读取 json 字符串时出现段错误

转载 作者:行者123 更新时间:2023-11-30 15:08:20 29 4
gpt4 key购买 nike

我正在尝试读取 json 字符串并打印,它产生段错误(核心转储)。我认为错误是由于输入字符串引起的,但不太确定。

这是代码

代码:

 #include <json/json.h>
#include <stdio.h>

void json_parse(json_object * jobj);

int main(){

char * string = "{"
"\"coooooool\": { "
"\"name\" : \"coooooooooool\","
"\"name\" : 1"
"\"}"
"\"}";

printf ("JSON string: %sn", string);
json_object * jobj = json_tokener_parse(string);
json_parse(jobj);


return 0;
}

void json_parse(json_object * jobj) {
enum json_type type;
json_object_object_foreach(jobj, key, val) {
type = json_object_get_type(val);
switch (type)
{
case json_type_int: printf("type: json_type_int, ");
printf("value: %dn", json_object_get_int(val));
break;
}
}
}

我使用 valgrind 运行输出二进制文件以正确检查错误

我在使用 valgrind 运行时遇到此错误

==14573== Memcheck, a memory error detector
==14573== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==14573== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==14573== Command: ./a.out
==14573==
==14573== Invalid read of size 4
==14573== at 0x40491F8: json_object_get_object (in /usr/lib/i386-linux-gnu/libjson.so.0.0.1)
==14573== by 0x80485E5: main (in /var/www/json/a.out)
==14573== Address 0xfffffff5 is not stack'd, malloc'd or (recently) free'd
==14573==
==14573==
==14573== Process terminating with default action of signal 11 (SIGSEGV)
==14573== Access not within mapped region at address 0xFFFFFFF5
==14573== at 0x40491F8: json_object_get_object (in /usr/lib/i386-linux-gnu/libjson.so.0.0.1)
==14573== by 0x80485E5: main (in /var/www/json/a.out)
==14573== If you believe this happened as a result of a stack
==14573== overflow in your program's main thread (unlikely but
==14573== possible), you can try to increase the size of the
==14573== main thread stack using the --main-stacksize= flag.
==14573== The main thread stack size used in this run was 8388608.
JSON string: {"coooooool": { "name" : "coooooooooool","name" : 1"}"}n==14573==
==14573== HEAP SUMMARY:
==14573== in use at exit: 0 bytes in 0 blocks
==14573== total heap usage: 17 allocs, 17 frees, 1,511 bytes allocated
==14573==
==14573== All heap blocks were freed -- no leaks are possible
==14573==
==14573== For counts of detected and suppressed errors, rerun with: -v
==14573== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)

最佳答案

你的问题很简单:你的 json 字符串中有错误。
您的 json 字符串如下(不转义引号):

{"coooooool": { "name" : "coooooooooool","name" : 1"}"}

两个键具有相同的名称,并且字符串的最后两个双引号字符完全不合适。
该字符串不是有效的 json,因此 json_tokener_parse 返回 NULL。
您应该执行错误检查以捕获解析字符串的失败,即添加如下检查:

if(jobj == NULL) {
// recover from the error or quit the program
}

使用您的代码,json_object_object_foreach 收到一个 NULL 指针,导致段错误。

关于c - 读取 json 字符串时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37395359/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com