gpt4 book ai didi

c++ - cudaFree 和 cudaFreeHost 无法释放堆分配的内存

转载 作者:行者123 更新时间:2023-11-30 01:46:42 27 4
gpt4 key购买 nike

我编写了一个类,其中堆中的构造函数内存是使用 cudaMallocHost() 和 cudaMalloc() 分配的。

如果我尝试释放内存 cudaFree() 或 cudaFreeHost(),GPUassert 会提示:

GPUassert: invalid device pointer ../src/main.cu 97

GPUassert: invalid argument ../src/main.cu 95

我在计算能力为 2.1 的设备上使用 CUDA TK 7.0。

我想我遗漏了一些基本的东西。我可以创建在设备上分配内存的对象吗?

class FreeMe {

public:
FreeMe(int size);
~FreeMe(void);

private:
float *A, *dA;
int size;
};

FreeMe::FreeMe(int size) :
size(size) {
gpuErrchk(cudaMallocHost((void** ) &A, sizeof(float) * size));
gpuErrchk(cudaMalloc((void** ) &dA, sizeof(float) * size));
}
FreeMe::~FreeMe(void) {
std::cout << "FreeMe obj deleted: Free ..." << std::endl;
gpuErrchk(cudaFreeHost(A));
gpuErrchk(cudaFree(dA));
}

int main(int argc, char **argv) {
int size = 3;

FreeMe free1(size);

cudaDeviceReset();
std::cout << "Program terminated successfully." << std::endl;
return EXIT_SUCCESS;
}

最佳答案

该错误是由于您调用了 cudaDeviceReset() 引起的。看着its documentation :

Explicitly destroys and cleans up all resources associated with the current device in the current process. Any subsequent API call to this device will reinitialize the device.

Note that this function will reset the device immediately. It is the caller's responsibility to ensure that the device is not being accessed by any other host threads from the process when this function is called.

请注意,您的对象将在该调用之后 被销毁。当您重置设备时,它将无法释放内存(这是在析构函数中完成的)。

一种解决方案是使用newdelete 在堆上分配您的对象,因此您可以delete 您的free1 对象之前 调用cudaDeviceReset()

关于c++ - cudaFree 和 cudaFreeHost 无法释放堆分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32763555/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com