I have the following code (assume everything is defined properly):
#include "OurIncludes.h"
#include <ctime>
__global__ void kernel_testing(int *d_intersects, Circle *part1, Circle *part2)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
int j = blockIdx.y * blockDim.y + threadIdx.y;
if (i < 10 && j < 10) {
int index = i + j * 10;
d_intersects[index] = part1[i].intersect(part2[j]);
}
}
int main(void)
{
dim3 GRID(1, 1);
dim3 BLOCK(10, 10);
short randomNum;
RandObj randGenerator;
Circle* obj = new Circle[10];
Circle* obj2 = new Circle[10];
Circle *d_obj;
Circle *d_obj2;
int intersects[100];
int *d_intersects;
if (cudaSuccess != cudaMalloc((void **)&d_obj, sizeof(Circle) * 10)) {
fprintf(stderr, "Failed to allocate memory for d_result\n");
}
if (cudaSuccess != cudaMalloc((void **)&d_obj2, sizeof(Circle) * 10)) {
fprintf(stderr, "Failed to allocate memory for d_result\n");
}
if (cudaSuccess != cudaMalloc((void **)&d_intersects, sizeof(int) * 100)) {
fprintf(stderr, "Failed to allocate memory for d_result\n");
}
for (int i = 0; i < 10; i++) {
obj[i] = (*randGenerator.makeRandomCircle());
}
for (int i = 0; i < 10; i++) {
obj2[i] = (*randGenerator.makeRandomCircle());
}
size_t size = sizeof(Circle);
if (cudaSuccess != cudaMemcpy(d_obj, obj, size * 10, cudaMemcpyHostToDevice)) {
fprintf(stderr, "Failed to copy data to d_obj\n");
}
if (cudaSuccess != cudaMemcpy(d_obj2, obj2, size * 10, cudaMemcpyHostToDevice)) {
fprintf(stderr, "Failed to copy data to d_obj2\n");
}
kernel_testing << < GRID, BLOCK >> >(d_intersects, d_obj, d_obj2);
cudaError_t s = cudaMemcpy(intersects, d_intersects, sizeof(int) * 100, cudaMemcpyDeviceToHost);
fprintf(stderr, "Error is: %s", cudaGetErrorString(s));
cudaFree(d_intersects);
cudaFree(d_obj);
cudaFree(d_obj2);
return 0;
}
For some reason, the code always fails at cudaMemcpyDeviceToHost
, and I cannot see a reason as to why it should. I've tried launching with different objects (triangles, spheres etc.), but it always fails when I need to copy data back from device to host. Any help and/or suggestion is appreciated, I'm very new to programming using CUDA. Thanks.
EDIT: The error code says that an illegal memory access was encountered, but I don't see why that should happen.
EDIT 2: So I've removed all the double pointers and "flattened" my arrays, yet I still have the same problem. I'm completely out of ideas now.