我的在线商店产生分段错误,我无法弄清楚原因

问题描述 投票:-3回答:1

我正在为高级C ++课程做家庭作业。该程序模拟在线商店的后端。幸运的是,有一个自动编程器用于分配,我的产品和客户类通过了每个测试用例,但是我的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());
    }        
}

c++ oop segmentation-fault
1个回答
0
投票

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

    product->getID();

    Store::getProduct()

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

© www.soinside.com 2019 - 2024. All rights reserved.