cudaMalloc 以静态大小成功,但以动态计算大小失败

cudaMalloc succeeded with static size but failed with dynamically calculated size

我试图在 GPU 上分配大约 2.75G 内存。 size为'static'时可以(编译时知道),如果size为'dynamic'则失败。

我在装有 CentOS 7.1、Cuda 7.5、2 x TtianX 卡、intel 4790K、32GB 内存的盒子上

代码:

#include <cstdio>
#include <cuda_runtime.h>

int main() {
    int item_count = 21217344;
    int dim = 128;

    unsigned char * data_dev;
    size_t mem_size = item_count * dim * sizeof(unsigned char);
    printf("memory to alloc %u\n", mem_size);
    int r = cudaMalloc((void **)&data_dev, mem_size);
    if(r) {
        printf("memory alloc failed!\n");
    }

    size_t mem_size_static = 2715820032; // 21217344 * 128 = 2715820032;
    r = cudaMalloc((void **)&data_dev, mem_size_static);
    if(!r) {
        printf("memory alloc succeeded!\n");
    }

}

保存到'test_mem.cu'然后编译:

 /usr/local/cuda/bin/nvcc test_mem.cu 

和运行它:

[root@localhost test]# ./a.out 
memory to alloc 2715820032
memory alloc failed!
memory alloc succeeded!

对此有什么想法吗?

int item_count = 21217344;
int dim = 128;

那些是 ints,它们的乘积是 2715820032,溢出为 -1579147264。请求负内存量当然是错误的,cudaMalloc 失败。

你想要的是要么声明那些具有更宽类型的组件(例如 std::size_t),要么将任一组件转换为更宽的类型 before multiply,以及一切会很好用的。

旁注:如果您使用 C++ 的 std::cout 而不是 printf 或适当的大小格式说明符 %z.

,您会立即发现该错误