CodexBloom - Programming Q&A Platform

Segmentation fault when using std::vector with custom allocator in C++20 across multiple threads

👀 Views: 49 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-22
c++ multithreading stdvector customallocator cpp

I'm not sure how to approach I'm encountering a segmentation fault when using `std::vector` with a custom allocator in a multi-threaded environment... My custom allocator is derived from `std::allocator`, and I'm trying to allocate and deallocate memory for a vector concurrently in different threads. Here's a simplified version of my custom allocator: ```cpp #include <memory> #include <iostream> template <typename T> struct MyAllocator : std::allocator<T> { using value_type = T; MyAllocator() = default; template <typename U> MyAllocator(const MyAllocator<U>&) noexcept {} T* allocate(std::size_t n) { std::cout << "Allocating " << n << " objects." << std::endl; return std::allocator<T>::allocate(n); } void deallocate(T* p, std::size_t n) { std::cout << "Deallocating " << n << " objects." << std::endl; std::allocator<T>::deallocate(p, n); } }; ``` I've created a `std::vector` like this: ```cpp std::vector<int, MyAllocator<int>> vec; ``` In one thread, I'm pushing back elements: ```cpp void addToVector() { for (int i = 0; i < 1000; ++i) { vec.push_back(i); } } ``` In another thread, I'm attempting to access and print the elements: ```cpp void printVector() { for (int i = 0; i < 1000; ++i) { std::cout << vec[i] << " "; } } ``` Using `std::thread`, I run both functions: ```cpp std::thread t1(addToVector); std::thread t2(printVector); ``` The program compiles and runs, but after a while, I get a segmentation fault, typically when the `printVector` function tries to access elements that are not fully constructed or have been invalidated. I'm using GCC 10.2 with C++20 standard. I've tried adding mutexes around the vector access, but that leads to deadlocks. What would be the best approach to handle this, or is there something wrong with my allocator implementation? Thanks, I really appreciate it!