我的在线商店生成细分错误,我无法弄清原因

时间:2019-04-08 17:53:05

标签: c++ oop segmentation-fault

我正在为高级C ++课程进行家庭作业。该程序模拟在线商店的后端。幸运的是,有一个自动评分器用于分配,我的Product和Customer类通过了每个测试用例,但是我的Store类在某处存在分段错误,并且由于自动评分器对每个函数进行了单元测试,因此我知道该错误发生在addProduct( ),它也可能发生在getProduct()中,因为addProdcut()调用了getProduct()。

我不确定错误发生在哪里,我尝试使用驱动程序代码在我的机器上重新创建它,但是自动平地机只是说发生了分段错误,没有告诉我哪里。 https://imgur.com/a/W1dzI7K

//numProducts is a static int and a data member of the Store class
static int Store::numProducts = 0;
//The products array is an array of Product pointers maximum size 100
Product* products[100];

//Each product has a unique id of type integer

bool Store::addProduct(int productID, const char productName[])
{
    Product* product = getProduct(productID);
    if (numProducts == 99) { return false; }
    else if (product != nullptr) { return false; }
    else
    {
        Product* newProduct = new Product(productID, productName);
        products[numProducts] = newProduct;
        numProducts++;
        return true;
    }
}

Product* Store::getProduct(int productID)
{
    for (Product* product : products)
    {
        if (product->getID() == productID) {return product;}
    }
    return nullptr;
}

int Product::getID() const { return id; }

//here is the Product constructor, however i know that this is perfectly fine since the product class passes all unit-testing.

Product::Product(int productID, const char productName[]) :
    id(productID), inventory(0), numSold(0), totalPaid(0.0) {
        setName(productName);
        strcpy_s(this->description, "");
    }
//And here is the setName function in case you want to recreate this
void Product::setName(const char productName[]) {
    if (strlen(productName) > 0) {
        strcpy_s(this->name, productName);
    }
    else {
        //Counter is a static int
        counter++;
        ostringstream oss;
        oss << "Product " << counter;
        strcpy_s(this->name, oss.str().c_str());
    }        
}

1 个答案:

答案 0 :(得分:0)

似乎您忘记了在调用其方法之前对 product (与 nullptr 比较)进行零检查

    product->getID();

    Store::getProduct()

很明显,用零初始化指针调用方法不是一个好主意。