rapidjson icon indicating copy to clipboard operation
rapidjson copied to clipboard

In `SetObjectRaw`, Member* m might be nullptr without any check.

Open ken4647 opened this issue 1 year ago • 1 comments

For some reasons, if the memory is not enough for DoAllocMembers(count, allocator), it will got nullptr as return value. However, there seems to be no checks or assert for this sititutation. It took me lots of hours to find the reason, so I want to fix it up and strengthen the robustness for this library. The detailed code is in rapidjson/include/rapidjson/document.h, and it looks like:

    //! Initialize this value as object with initial data, without calling destructor.
    void SetObjectRaw(Member* members, SizeType count, Allocator& allocator) {
        data_.f.flags = kObjectFlag;
        if (count) {
            Member* m = DoAllocMembers(count, allocator);
            SetMembersPointer(m);
            printf("the ptr of m is %p\n", m);
            std::memcpy(static_cast<void*>(m), members, count * sizeof(Member));
#if RAPIDJSON_USE_MEMBERSMAP
            Map* &map = GetMap(m);
            MapIterator* mit = GetMapIterators(map);
            for (SizeType i = 0; i < count; i++) {
                printf("members[%d].name.data_ = %s\n", i, m[i].name.data_.GetString());
                new (&mit[i]) MapIterator(map->insert(MapPair(m[i].name.data_, i)));
            }
#endif
        }
        else
            SetMembersPointer(0);
        data_.o.size = data_.o.capacity = count;
    }

I got the ptr of m is 0 when debugging for Migrating the application to MCUs, which have very limited RAMs for malloc. Though the final solution is just to adjust the defination of RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY to 1024.

ken4647 avatar Oct 21 '24 06:10 ken4647

Some necessary assertions have been added to the #2313 .

ken4647 avatar Oct 21 '24 06:10 ken4647