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

时间:2015-09-24 14:08:22

标签: c++ oop cuda

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

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

  

GPUassert:设备指针无效../src/main.cu 97

  

GPUassert:无效参数../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;
}

1 个答案:

答案 0 :(得分:4)

错误是由您致电cudaDeviceReset()引起的。看its documentation

  

明确地销毁和清理与之相关的所有资源   当前进程中的当前设备。任何后续的API调用   设备将重新初始化设备。

     

请注意,此功能会立即重置设备。它是   呼叫者有责任确保设备不存在   当此函数从进程中的任何其他主机线程访问时   被称为。

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

一种解决方案是使用newdelete在堆上分配您的对象,因此您可以delete free1对象 之前cudaDeviceReset()SELECT SEC_TO_TIME(SUM(TIME_TO_SEC( `your_column_name` ) ) ) AS timeSum FROM YourTableName