gpt4 book ai didi

c - C中的Json解析和字符串管理

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

考虑以下功能:

int get_timestamp(json_object *json_obj, double *timestamp) {
json_object *value_obj;
int status;
if (json_object_object_get_ex(json_obj, "timestamp", &value_obj)) {
if (json_object_is_type(value_obj, json_type_double)) {
*timestamp = json_object_get_double(value_obj);
status = JSONPARSER_OK;
}
else
status = JSONPARSER_EBADTYPE;
} else
status = JSONPARSER_ENODENOTFOUND;
free(value_obj);
return status;
}

int get_display_name(json_object *json_obj, char **display_name) {
json_object *value_obj;
int status;
const char* holder;
if (json_object_object_get_ex(json_obj, "display_name", &value_obj)) {
if (json_object_is_type(value_obj, json_type_string)) {
// The returned string memory is managed by the json_object and will
// be freed when the reference count of the json_object drops to zero.
holder = json_object_get_string(value_obj);
strcpy(*display_name, holder);
status = JSONPARSER_OK;
}
else
status = JSONPARSER_EBADTYPE;
} else
status = JSONPARSER_ENODENOTFOUND;
free(value_obj);
return status;
}

int get_organization(json_object *json_obj, char **organization) {
json_object *value_obj;
int status;
const char* holder;
if (json_object_object_get_ex(json_obj, "organization", &value_obj)) {
if (json_object_is_type(value_obj, json_type_string)) {
// The returned string memory is managed by the json_object and will
// be freed when the reference count of the json_object drops to zero.
holder = json_object_get_string(value_obj);
strcpy(*organization, holder);
status = JSONPARSER_OK;
}
else
status = JSONPARSER_EBADTYPE;
} else
status = JSONPARSER_ENODENOTFOUND;
free(value_obj);
return status;
}

用作:

json_object *response_obj, *idp_obj;
int status;
char *display_name;
char *organization;
response_obj = json_tokener_parse(raw_data);
json_object_object_get_ex(response_obj, "idp", &idp_obj);

get_timestamp(response_obj, timestamp);
get_display_name(idp_obj, &display_name);
get_organization(idp_obj, &organization);

free(idp_obj);
free(response_obj);
return status;

发生了什么:

1)通过删除 get_organization(idp_obj, &organization); 一切似乎工作正常;

2)通过删除 get_display_name(idp_obj, &display_name); 一切似乎再次正常工作;

3) 使用“原样”代码,方法 get_organization 内使用的 strcpy 存在错误:

No source available for "__strcpy_sse2_unaligned() at 0x7ffff763f001" 

我真的很想理解这种行为,以提高我对这种令人惊奇但困难的语言的知识。

最佳答案

该错误消息是调试器错误消息,因为它位于无法找到源代码的函数中。您唯一需要做的就是沿着函数调用堆栈向上查找,直到到达代码。

至于为什么调试器在该函数中停止,这确实应该是另一个问题,但无论如何我都会回答它:这是因为未定义的行为,因为目标您传递给它的指针是一个未初始化的局部变量:display_name 。在您调用 get_display_name 的代码中您声明局部变量 display_name ,但你没有初始化它。未初始化的非静态局部变量的值不确定,在没有初始化的情况下使用它们会导致未定义的行为。

对于这个问题,你基本上有两种解决方案:要么声明 display_name作为固定大小的数组,或使用使其指向有效分配的内存,例如使用 malloc .

您也会遇到同样的问题 organization变量。

关于c - C中的Json解析和字符串管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32228886/

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