UB in std::vector::operator=
- Dominant language
- LLVM
- Stars
- 40.5k
- Forks
- 18.7k
- PR merge metrics
- PR metrics pending
Description
I believe the following reproducer demonstrate an UB in `std::vector` implementation of `operator=` incase if we are using a custom allocator:
```c++
#include
#include
#include
// Simple custom allocator that checks it's not default-constructed
template
class CustomAllocator {
public:
using value_type = T;
using propagate_on_container_copy_assignment = std::true_type;
using propagate_on_container_move_assignment = std::true_type;
using propagate_on_container_swap = std::true_type;
CustomAllocator() : valid_(false) {}
CustomAllocator(bool valid) : valid_(valid) {}
template
CustomAllocator(const CustomAllocator& other) : valid_(other.valid_) {}
T* allocate(std::size_t n) {
if (!valid_) {
std::cerr << "Allocate called on invalid allocator\n";
std::abort();
}
return static_cast(::operator new(n * sizeof(T)));
}
void deallocate(T* p, std::size_t n) {
if (!valid_) {
std::cerr << "Deallocate called on invalid allocator\n";
std::abort();
}
::operator delete(p);
}
bool operator==(const CustomAllocator&) const = default;
private:
bool valid_;
};
int main() {
CustomAllocator alloc(true);
std::vector> v1(alloc);
std::vector> v2;
v1.push_back(1);
v2 = v1;
return 0;
}
```
The problem is observed at runtime. when v2 is constructor we do not call allocator, but when v2 is assigned we invoke deallocate with `(nullptr, 0)`. This is UB I believe and should be adressed in the library.
Contributor guide
Research direction
Start with the supplied C++ reproducer and the std::vector::operator= entry point, focusing on copy assignment with a default-constructed custom allocator. Verify whether deallocate(nullptr, 0) is reached and whether that violates the allocator requirements. Done means confirming the behavior and, if it is a library defect, adding a regression test and correcting the implementation.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100