我是 CUDA 的新手,我想使用 cudaHostAlloc
。我能够将我的问题隔离到以下代码。使用 malloc
进行主机分配工作,使用 cudaHostAlloc
导致段错误,可能是因为分配的区域无效?当我在这两种情况下转储指针时,它都不是空的,所以 cudaHostAlloc
返回一些东西......
作品
in_h = (int*) malloc(length*sizeof(int)); //works
for (int i = 0;i<length;i++)
in_h[i]=2;
没用
cudaHostAlloc((void**)&in_h,length*sizeof(int),cudaHostAllocDefault);
for (int i = 0;i<length;i++)
in_h[i]=2; //segfaults
独立代码
#include <stdio.h>
void checkDevice()
{
cudaDeviceProp info;
int deviceName;
cudaGetDevice(&deviceName);
cudaGetDeviceProperties(&info,deviceName);
if (!info.deviceOverlap)
{
printf("Compute device can't use streams and should be discarded.");
exit(EXIT_FAILURE);
}
}
int main()
{
checkDevice();
int *in_h;
const int length = 10000;
cudaHostAlloc((void**)&in_h,length*sizeof(int),cudaHostAllocDefault);
printf("segfault comming %d\n",in_h);
for (int i = 0;i<length;i++)
{
in_h[i]=2; // Segfaults here
}
return EXIT_SUCCESS;
}
~
调用
[id129]$ nvcc fun.cu
[id129]$ ./a.out
segfault comming 327641824
Segmentation fault (core dumped)
详情
程序在集群上以交互模式运行。有人告诉我,从计算节点调用程序会将其推送到集群。其他自制玩具 cuda 代码没有遇到任何问题。
编辑
cudaError_t err = cudaHostAlloc((void**)&in_h,length*sizeof(int),cudaHostAllocDefault);
printf("Error status is %s\n",cudaGetErrorString(err));
给出驱动程序错误...
Error status is CUDA driver version is insufficient for CUDA runtime version
最佳答案
始终检查错误。 cudaHostAlloc
可能无法分配任何内存。如果它失败了,你不是在逃避,而是在写入未分配的地址空间。使用 malloc
时,它会根据请求分配内存并且不会失败。但也有 malloc 也可能导致失败的情况,因此最好在写入指针之前对指针进行检查。
为了将来,最好做这样的事情
int *ptr = NULL;
// Allocate using cudaHostAlloc or malloc
// If using cudaHostAlloc check for success
if (!ptr) ERROR_OUT();
// Write to this memory
EDIT(对问题中编辑的回应)
错误消息表明与工具包相比,您的驱动程序较旧。如果您不想暂时卡住,请尝试下载与您的驱动程序兼容的旧版本 cuda 工具包。您可以将它安装在您的用户帐户中并暂时使用它的 nvcc + 库。
关于c - malloc 有效,cudaHostAlloc 段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13594205/