[英]My Online store generates a segmentation fault and i cant figure out why
我正在為高級 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());
}
}
在調用其方法之前,您似乎忘記對產品進行零檢查(將其與nullptr進行比較)
product->getID();
在
Store::getProduct()
顯然,通過零初始化指針調用方法不是一個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.