我卡在这个问题上了。问题在于执行 cudaMalloc
时出现段错误。这就是我正在做的:
class AllInput {
public:
int numProducts;
Product * products;
public:
AllInput(int _numProducts, Product * _products);
};
class Product {
public:
int sellingPrice; //Ri
struct DemandDistribution observationDemand; //C2i
public:
Product(
LucyDecimal _sellingPrice, //Ri
LucyDecimal _costPriceAssmbly);
};
然后我有一个创建它的函数:
AllInput* in1() {
struct DemandDistribution * _observationDemand1 =
(DemandDistribution*) malloc(sizeof(DemandDistribution));
// set values
Product * product1 = new Product(165,_observationDemand1);
//initialize product2, product3, product4
Product *products = (Product*) malloc(4 * sizeof(Product*)); //line-a
products[0] = * product1;
products[1] = * product2;
products[2] = * product3;
products[3] = * product4;
AllInput* all = new AllInput(4, products);
return all;
}
当我尝试这样做时:
void mainRun(){
AllInput* in = in1();
AllInput* deviceIn;
deviceIn = new AllInput(0, NULL);
cudaMalloc((void**) &deviceIn, sizeof(AllInput*)); //line-b
line-b
抛出段错误。如果我将 line-a
更改为 Product products[4] = { *product1, *product2, *product3, *product4};
那么错误就会消失。这不是解决方案,因为 products
被解构了
更改产品
如何影响cudaMalloc
?我们没有向 cudaMalloc
传递任何参数,但它为什么会影响它?
我该怎么做才能避免这种情况?
最佳答案
可能是线的问题
(Product*) malloc(4 * sizeof(Product*));
您创建了一个包含四个指针的数组。如果 Product
大于指针(在您的示例中很可能),那么接下来的 4 行是缓冲区溢出。可能堆已损坏并且 malloc 内部数据被覆盖 - 此外,您还可以覆盖堆的一些随机部分。
该行应该是 (Product*) malloc(4 * sizeof(Product))
、(Product *)malloc(sizeof(Product[4]))
或甚至更好 new Product[4]
(请注意,在最后一种情况下,您应该通过 delete[]
释放)。
关于c++ - CudaMalloc 抛出 sigabrt 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23079987/