(int)-1的CUDA内核printf使用%d说明符给出了错误的输出

Mar*_*ann 1 printf cuda format-specifiers

用C告诉我的电脑

printf("%d",(int)-1);
Run Code Online (Sandbox Code Playgroud)

我确实希望,并且通常也得到'-1'响应.但是,在我的基于Ubuntu的Cuda 5.0上使用的特斯拉M2090 Nvidia卡这个无辜的演示程序

/** cheese.cu */
#include <iostream>
#include <cuda.h>
#include <cstdio>

using namespace std;

template<typename T> struct SpacePtr
  { size_t size; T* ptr; };

 __global__ void f(SpacePtr<int>* sp)
{
  printf("This _is_ a 'minus one' or ain't it: %d\n",(int)-1);
  // Note: All appears to work fine with %lu instead of %zd
  // Still: How does the size value affect the -1?
  printf("On DEV: Size: %zd, Minus One: %d\n",sp->size,(int)-1);
}

int main()
{
  SpacePtr<int> data; data.ptr = 0; data.size = 168;
  SpacePtr<int>* devPtr = 0;
  cudaMalloc(&devPtr,1);
  cudaMemcpy(devPtr,&data,sizeof(SpacePtr<int>),cudaMemcpyHostToDevice);
  f<<<1,1,0,0>>>(devPtr);
  cudaError_t err = cudaGetLastError();
  cout << "The last error code was " << err << " (" <<
    cudaGetErrorString(err) << ")" << endl;
  cudaDeviceSynchronize();
}
Run Code Online (Sandbox Code Playgroud)

编译并通过调用

nvcc -arch=sm_20 cheese.cu && ./a.out
Run Code Online (Sandbox Code Playgroud)

产生输出:

The last error code was 0 (no error)
This _is_ a 'minus one' or ain't it: -1
On DEV: Size: 168, Minus One: 10005640
Run Code Online (Sandbox Code Playgroud)

最后一个数字实际上是某种随机数(两个子后续调用会返回不同的结果),好像在内存分配中有些不对劲.-1之前的(int)已经是试验和错误.原计划没有.

这里有一个问题:有人看到,为什么不写-1,如果是的话,你能告诉我为什么吗?非常感谢,马库斯.

ter*_*era 5

如果查看CUDA C编程指南的附录B.20.1"格式说明符",您会发现不支持z修饰符%zd.您必须转换为unsigned long并使用%lu格式说明符:

printf("On DEV: Size: %lu, Minus One: %d\n",(unsigned long)(sp->size), (int)-1);
Run Code Online (Sandbox Code Playgroud)