user3667089 user3667089 - 1 month ago 11
C++ Question

Error when copying vector bool to CUDA memory

I encountered a compilation error where copying a bool vector to cuda memory will fail

bool *gpu;

cudaMalloc(reinterpret_cast<void **>(&gpu), 100);

std::vector<bool> cpu(100);

for(int i=0;i<100;i++){
cpu[i]=true;
}

cudaMemcpy(gpu, cpu.data(), 100*sizeof(bool), cudaMemcpyHostToDevice);


It returns

error: invalid use of void expression cudaMemcpyHostToDevice);


but the same code with a float vector will compile.

float *gpu;

cudaMalloc(reinterpret_cast<void **>(&gpu), 100);

std::vector<float> cpu(100);

for(int i=0;i<100;i++){
cpu[i]=i;
}

cudaMemcpy(gpu, cpu.data(), 100*sizeof(float), cudaMemcpyHostToDevice);


Why is this happening?

Answer

vector<bool> is a mistake from C++98 that we cannot get rid of (at least in terms of occupying the name). The standard recommends that it keeps the storage as a space-optimized representation of bits and that's what most implementations do.

You can work around this by using vector<uint8_t> instead.

Comments