Shown bellow is a simplified version of the code that I’m working with, when I don’t use cudaMallocManaged
and just initialize everything using the new
keyword, everything runs just fine. I have narrowed down the problem to the way the elements in the array are initialized in the for loop, but I cannot figure out what is going wrong here. When printing comparing the pointers everything seems to be the way it should yet it produces a segmentation fault.
#include <iostream>
class B
{
public:
__device__ __host__ virtual void test() = 0;
};
class A: public B
{
public:
__device__ __host__ A(int x) {number = x;};
__device__ __host__ void test() {printf("test called!\n");}
int number;
};
int main(int argc, char const *argv[])
{
// Size of array.
static const int count = 2;
// Create array of pointers to A objects in memmory.
B** list; // = new B*[count];
cudaMallocManaged(&list, count*sizeof(B*));
// Create objects for in array.
for (int i = 0; i < count; i++)
{
A* tempPointer;
cudaMallocManaged(&tempPointer, sizeof(A));
*tempPointer = A(500);
list[i] = tempPointer;
}
// Gives a segmentation fault.
for (int i = 0; i < count; i++)
list[i]->test();
// Free memmory.
for (int i = 0; i < count; i++)
cudaFree(list[0]);
cudaFree(list);
}
Using this for loop instead will result in working code, but I really need to use cudaMallocManaged
so this is not an option:
for (int i = 0; i < count; i++)
{
A* tempPointer = new A(500);
list[i] = tempPointer;
}