码迷,mamicode.com
首页 > Web开发 > 详细

解决JSONCPP 0.10.2的一个Bug

时间:2015-04-25 09:25:15      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:jsoncpp 0.10.2 bug   数组   

最近在使用jsoncpp 0.10.2的过程中碰到一个bug,创建的数组,无法超过5个元素,测试代码如下:


int j = 0;
int count = 20;
Json::Value root;
Json::Value item;
for (int i = 0; i < count; i++)
{
root[i] = i;
j = root.size();
}


在我的实际项目中,如果数组只有1个是元素(该元素稍微有点大的JSON对象),也有可能出现这个元素的值错误的故障,超过5个肯定出错。


在github上创建了一个issue,作者响应很快,但由于开发环境不同,他测试各个分支的代码结果都正常,不能重现故障。我在几天里,陆续调试过几次后,终于逐渐发现了故障原因:


在jsoncpp的源码里进行Debug,发现实际创建的数组成员数量并没有少,但 value_.map_ 的键CZString的成员index_是 0,1,2,3,4,0,1,2,3,4, 0,1,2,3,4,0,1,2,3,4,按正确代码应该是从0一直递增到19。而数组的size()函数是按最后一对键值的index_加1来计算大小的:

case arrayValue: // size of the array is highest index + 1
if (!value_.map_->empty()) {
ObjectValues::const_iterator itLast = value_.map_->end();
--itLast;


return (*itLast).first.index() + 1;
    }
    return 0;


这里我不能理解作者不直接调用map的size()函数,虽然按最后一个元素的index_的值加1来计算数组大小在逻辑上无错误。发现这个环节的故障后,再经过几次调试和思考,发现了故障原因所在:


Value::CZString::CZString(const CZString& other)
    : cstr_(other.storage_.policy_ != noDuplication && other.cstr_ != 0
                ? duplicateStringValue(other.cstr_, other.storage_.length_)
                : other.cstr_)
{
  storage_.policy_ = (other.cstr_
                 ? (other.storage_.policy_ == noDuplication
                     ? noDuplication : duplicate)
                 : other.storage_.policy_);
  storage_.length_ = other.storage_.length_;
}


以上这个拷贝构造函数里没有处理index_这个成员变量。加上以下1行,解决了故障:


this->index_ = other.index_;

再次更新issue,作者确认是bug,同时对该bug未影响其他用户感到奇怪。

解决JSONCPP 0.10.2的一个Bug

标签:jsoncpp 0.10.2 bug   数组   

原文地址:http://blog.csdn.net/gzliudan/article/details/45264201

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!