用C告诉我的电脑
printf("%d",(int)-1);
我确实期望并且通常也会得到“-1”的响应。然而,在我的 Tesla M2090 Nvidia 卡上,我的基于 Ubuntu 的 Cuda 5.0 与这个无辜的演示程序对话
/** 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();
}
通过编译和调用
nvcc -arch=sm_20 cheese.cu && ./a.out
产生输出:
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
最后一个数字实际上是某种随机数(两次后续调用返回不同的结果),就好像内存分配有问题一样。 -1 之前的 (int) 已经是反复试验了。原程序没有。
问题是:有人看到为什么没有写 -1 吗?如果看到了,请告诉我为什么?非常感谢,马库斯。
最佳答案
如果你勾选appendix B.32.1 "Format Specifiers"在 CUDA C Programming Guide 中,您会发现 %zd
中的 z
修饰符不受支持。您必须转换为 unsigned long
并使用 %lu
作为格式说明符:
printf("On DEV: Size: %lu, Minus One: %d\n",(unsigned long)(sp->size), (int)-1);
关于(int) -1 的 CUDA 内核 printf 给出带有 %d 说明符的错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15198550/