我正在嘗試閱讀json字符串並打印,它正在生成段錯誤(核心轉儲)。我認爲錯誤是輸入字符串,但不是很確定。分段錯誤讀取json字符串
這裏是代碼
CODE:
#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_object * jobj'的內存在哪裏? json lib是做這個還是你負責?看起來你是,但我之前沒有使用過這個庫,所以仔細檢查。 '地址0xfffffff5不堆棧,malloc'd或(最近)free'd' ?? –