Is this a safe to resize a vector?

hello.

Is this a safe to resize a vector?

int* a;
int* b;
cudaMalloc((void**)(&a), aSize);
cudaMemcpy(a, 1, aSize);
cudaMalloc((void**)(&b), bSize);
cudaMalloc((void**)(&a), aSize + expandSize);

It’s a memory leak. It’s not a good practice. Before you do the 2nd cudaMalloc on a, do a cudaFree on it. and of course this means you lose the previous contents.

If you want serious vector style behavior, you’re not going to get it with 3 lines of code.

1 Like

Thank you.

I will edit code like this. Is this OK?

int* a;
int* a_tmp;
int* b;
cudaMalloc((void**)(&a), aSize);
cudaMalloc((void**)(&a_tmp), aSize);
cudaMemset(a, 1, aSize);
cudaMalloc((void**)(&b), bSize);

cudaMemcpy(a_tmp, a, aSize);
cudaFree(a);
cudaMalloc((void**)(&a), aSize + expandSize);
cudaMemcpy(a,a_tmp,aSize);

Yes, I think that would work. It’s not actually compliant code (e.g. cudaMemcpy takes 4 arguments) but the idea seems correct. You might be able to simplify:

int *a;
int *a_tmp;
cudaMalloc(&a, aSize);
cudaMemset(a, 1, aSize);
cudaMalloc(&a_tmp, aSize + expandSize);
cudaMemcpy(a_tmp, a, aSize, cudaMemcpyDeviceToDevice);
cudaFree(a);
a = a_tmp;

This still doesn’t perfectly mimic std::vector behavior. For example, a vector will initialize its elements. We’re not doing that carefully here.

1 Like

Thank you.

I want to put this process in a loop and make it work the same way as std::vector or thrust::xxxx_vector resize.
Is this the fastest code? The size of “a” is not reduced.

int *a;
int *a_tmp;
cudaMalloc(&a, aSize);
cudaMemset(a, 1, aSize);

while(1){
// I understand that this code is wrong...
 cudaMalloc(&a_tmp, aSize + expandSize);
 cudaMemcpy(a_tmp, a, aSize, cudaMemcpyDeviceToDevice);
 cudaFree(a);
 a = a_tmp;

if (condition) break;
}

Oh, Sorry. I forgot to mention that the version is CUDA 10.2.

sorry. You lost me. I have no idea what you are trying to do.

Sorry for my cheap English. I needed to explain more details.

I would like to resize array in while loop like std::vector::resize.

// I want this process in CUDA...
std::vector<int> a(10,1);
while(1){
 // set n and k
 a.resize(n, k);
 if(condition) break;
}