1
在random_ints(b)
的調用中,在訪問陣列中的N-1
位置後,代碼運行到分段錯誤,與N
的值無關。雖然呼叫random_ints(a)
正常工作,並將所有值分配給數組a
。如果我使用數組的靜態分配,那麼代碼將完美運行。該代碼與NVIDIA CUDA Basics教程中提供的代碼完全相同,但不包括random_ints()
函數的實現。我已經嘗試了其他替代方法,替換main()
中的函數調用,或者分配另一個陣列並從random_ints()
返回main()
或刪除CUDA片段。沒有CUDA部分,函數調用將完美運行。使用CUDA中的設備malloc()獲取分段錯誤
我在尋找對這個問題的解釋。提前致謝。
#include<stdio.h>
#include<stdlib.h>
#define N 512
__global__ void add(int *a,int *b,int *c)
{
c[blockIdx.x]= a[blockIdx.x] + b[blockIdx.x];
}
void random_ints(int *x,int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\n%d",i);
x[i]=i;
}
}
int main()
{
int i;
int *a,*b,*c; //host copies of a,b,c
int *d_a, *d_b, *d_c; //device copies of a,b,c
int size =sizeof(int)*N;
//Allocate memories for device copies of a,b,c
cudaMalloc((void **)&d_a,size);
cudaMalloc((void **)&d_b,size);
cudaMalloc((void **)&d_c,size);
//Alloc space for host copies of a,b,c and setup input values
a=(int*)malloc(size);
random_ints(a,N);
b=(int*)malloc(size);
random_ints(b,N);
c=(int*)malloc(size);
//copy inputs to the device
cudaMemcpy(d_a, &a, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_b, &b, size, cudaMemcpyHostToDevice);
//Launch add() kernel on GPU
add<<<N,1>>>(d_a,d_b,d_c);
//copy results back to host
cudaMemcpy(&c, d_c, size, cudaMemcpyDeviceToHost);
for(i=0;i<N;i++)
{
printf("\nc= %d\n",c[i]);
}
//cleanup
free(a);free(b);free(c);
cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
return 0;
}
現在工作。感謝您的快速答覆。 – BooYah