-
Notifications
You must be signed in to change notification settings - Fork 83
Description
Description
The copy constructor of JsonWrapper class has undefined behavior (UB) that could cause random crashes or memory corruption.
Background
During a code audit of the vsag codebase's memory safety, we found that the JsonWrapper class's copy constructor checks uninitialized member variables during object construction.
JsonWrapper is a JSON wrapper class widely used within vsag, frequently used in parameter parsing, index configuration, and other scenarios. This bug has potential crash risk.
Problem
In src/json_wrapper.cpp:33-36, the copy constructor checks uninitialized member variables during object construction:
```cpp
JsonWrapper::JsonWrapper(const JsonWrapper& other) {
if (owns_json_) { // BUG: owns_json_ is uninitialized at this point
delete json_; // BUG: json_ is uninitialized, may delete wild pointer
}
json_ = new nlohmann::json();
owns_json_ = true;
// ...
}
```
This is a copy constructor (not an assignment operator). When called, the object has just been allocated memory, and both owns_json_ and json_ contain indeterminate values. The code incorrectly copied the cleanup logic from the assignment operator (operator=, line 44) to the constructor.
Solution
- Remove the
if (owns_json_) { delete json_; }code block from the copy constructor - Use member initializer list to properly initialize members before use
Fixed code:
```cpp
JsonWrapper::JsonWrapper(const JsonWrapper& other)
: json_(new nlohmann::json()), owns_json_(true) {
if (other.json_ != nullptr) {
*json_ = *other.json_;
}
}
```
Acceptance Criteria
- Copy constructor uses member initializer list
- Remove incorrect cleanup code from copy constructor
- Add unit tests for copy constructor scenarios
- Build passes
- Tests pass
Related
- Original task: agent-hive/tasks/2026-03-13-修复-jsonwrapper-拷贝构造函数-ub.md
- Related file:
src/json_wrapper.cpp,src/json_wrapper.h