CudaMalloc抛出sigabrt错误

CudaMalloc throws sigabrt error

本文关键字:错误 sigabrt 抛出 CudaMalloc      更新时间:2023-10-16

我被这个问题卡住了。问题是在执行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变成了解构的

更改productscudaMalloc有何影响?我们没有向cudaMalloc传递任何论点,但它为什么会影响它?我该怎么做才能避免这种情况?

问题可能是线路

(Product*) malloc(4 * sizeof(Product*));

创建一个由四个指针组成的数组。如果Product大于指针(在您的示例中可能是这样),那么接下来的4行就是缓冲区溢出。堆可能已损坏,malloc内部数据也被覆盖——此外,您还可以覆盖堆的一些随机部分。

该行应该是(Product*) malloc(4 * sizeof(Product))(Product *)malloc(sizeof(Product[4]))或更好的new Product[4](注意,在最后一种情况下,您应该在delete[]之前释放)。