我正在尝试使用json-c创建一个临时数据库。为此,我创建了一个简单的函数,它返回一个json对象,默认值为key:{quot;value":data}对,然后我尝试更新数据库中现有信号的值。但在这里,当我试图在值更新后打印数据库时,我遇到了分段错误。我不知道这里出了什么问题。
#include <stdio.h>
#include <string.h>
#include <json-c/json.h>
#include <stdlib.h>
static int db_created =0;
struct json_object* create_db(){
struct json_object* obj;
struct json_object* val;
obj = json_object_new_object();
val = json_object_new_object();
json_object_object_add(val,"val",json_object_new_int(1001));
json_object_object_add(obj,"key1",val);
json_object_object_add(val,"val",json_object_new_int(1002));
json_object_object_add(obj,"key2",val);
json_object_object_add(val,"val",json_object_new_int(1003));
json_object_object_add(obj,"key3",val);
json_object_object_add(val,"val",json_object_new_int(1004));
json_object_object_add(obj,"key4",val);
json_object_object_add(val,"val",json_object_new_int(1005));
json_object_object_add(obj,"key5",val);
return obj;
}
void run(){
struct json_object* db;
struct json_object* val;
struct json_object* temp;
struct json_object *db2;
val = json_object_new_object();
if(db_created == 1){
printf("database existn");
}else{
db = create_db();
printf("database = %sn",json_object_to_json_string(db));
db_created = 1;
}
//Get a value for key1
json_object_object_get_ex(db,"key1",&val);
printf("value = %sn",json_object_to_json_string(val));
//update the value for key1
json_object_object_add(val,"val",json_object_new_int(100));
json_object_object_add(db,"ke1",val);
//print database after updating key
printf("database = %sn",json_object_to_json_string(db));
}
int main(){
run();
return 0;
}
无法再现segmentation fault
。请提供更多详细信息,如编译器版本、构建命令行、操作系统版本、json-c版本。
顺便说一句,您的database building
至少有一个问题:您在create_db函数中重用了val。因此,上一个键的值总是会被下一次写入所覆盖。所以你的第一个数据库打印会有这样的输出:
database = {
"key1": {
"val": 1005
},
"key2": {
"val": 1005
},
"key3": {
"val": 1005
},
"key4": {
"val": 1005
},
"key5": {
"val": 1005
}
}
简单的缓解措施是为每个数据库项创建一个新对象。
struct json_object *create_db() {
struct json_object *obj;
struct json_object *val;
obj = json_object_new_object();
val = json_object_new_object();
json_object_object_add(val, "val", json_object_new_int(1001));
json_object_object_add(obj, "key1", val);
val = json_object_new_object();
json_object_object_add(val, "val", json_object_new_int(1002));
json_object_object_add(obj, "key2", val);
val = json_object_new_object();
json_object_object_add(val, "val", json_object_new_int(1003));
json_object_object_add(obj, "key3", val);
val = json_object_new_object();
json_object_object_add(val, "val", json_object_new_int(1004));
json_object_object_add(obj, "key4", val);
val = json_object_new_object();
json_object_object_add(val, "val", json_object_new_int(1005));
json_object_object_add(obj, "key5", val);
return obj;
}