简体   繁体   中英

CudaMalloc throws sigabrt error

I am stuck at this Issue. The issue is with segmentation fault while doing cudaMalloc . This is what I am doing:

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);
};

And then I have a function that creates it:

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;
}

When I try doing this:

void mainRun(){
    AllInput* in = in1();
    AllInput* deviceIn;
    deviceIn = new AllInput(0, NULL);
    cudaMalloc((void**) &deviceIn,  sizeof(AllInput*));  //line-b

line-b throws segmentation fault. If I change line-a to Product products[4] = { *product1, * product2, *product3, *product4}; then error disappears. That is not the solution as then products becomes deconstructed

How does changing products affect cudaMalloc ? We are not passing any argument to cudaMalloc , but why does it impact it? What can I do to avoid this?

Likely the problem is line

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

You create an array of four pointers. If Product is bigger then a pointer (which is likely in your example) then next 4 lines are an buffer overrun. Likely the heap is corrupted and the malloc internal data is overwritten - furthermore you could overwrite some random part of heap as well.

The line should be (Product*) malloc(4 * sizeof(Product)) , (Product *)malloc(sizeof(Product[4])) or even better new Product[4] (note that in last case you should free by delete[] ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM