I have very simple class using thrust device allocator.
I also have class on host side uses std::allocator. It works fine. But this one gives segmentation fault.
I am not sure what is wrong here. How can I use thrust lib to have a simple class with device pointer and fill constructor.
The simple code below is just gives me :
Segmentation fault
Execution failed with a non-zero exit code: 139
#include <thrust/device_ptr.h>
#include <thrust/fill.h>
#include <thrust/device_allocator.h> // Provides thrust::device_allocator
#include <cuda_runtime.h>
#include <iostream>
// The default allocator now uses the correct, fully qualified name:
// thrust::device_allocator<T>
template <typename T, typename Allocator = thrust::device_allocator<T>>
class flat1d {
public:
using value_type = T;
using size_type = std::size_t;
using allocator_type = Allocator;
// Use std::allocator_traits to get the correct Thrust pointer type
using pointer = typename std::allocator_traits<Allocator>::pointer;
private:
pointer data_ = nullptr;
size_type size_ = 0;
allocator_type alloc_;
public:
// Destructor: Cleans up the device memory using the allocator
~flat1d() {
if (data_ != nullptr) {
alloc_.deallocate(data_, size_);
}
}
flat1d() = default;
// The Fill Constructor
flat1d(size_type count, const value_type& value, const Allocator& alloc = Allocator())
: size_(count), alloc_(alloc)
{
if (count == 0) return;
// 1. Allocate device memory
data_ = alloc_.allocate(count);
// 2. Use Thrust fill algorithm
thrust::fill(data_, data_ + size_, value);
}
};
// --- Example Usage (Main function) ---
int main() {
const std::size_t N = 10;
const float FILL_VALUE = 3.14159f;
std::cout << "Creating flat1d array...\n";
// Calls the fixed fill constructor
flat1d<float> device_array(N, FILL_VALUE);
// Minimal output
std::cout << "Array initialization complete.\n";
return 0;
}