[英]My Online store generates a segmentation fault and i cant figure out why
I am working on a homework assignment for an advanced C++ course.我正在为高级 C++ 课程做家庭作业。 The program simulates the back-end of an online store.
该程序模拟在线商店的后端。 Luckily there is an autograder for the assignment and my Product and Customer classes pass every test case, however my Store class has a segmentation fault somewhere, and since the auto-grader unit-tests each function, I know the fault is occuring in addProduct(), it may also be occurring in getProduct() since addProdcut() calls getProduct().
幸运的是,作业有一个自动分级器,我的 Product 和 Customer 类通过了每个测试用例,但是我的 Store 类在某处存在分段错误,并且由于自动分级器对每个函数进行单元测试,因此我知道错误发生在 addProduct( ),它也可能发生在 getProduct() 中,因为 addProdcut() 调用了 getProduct()。
I am not sure where the fault is occurring, I've tried to recreate it on my machine using driver code, but the auto grader just says that a segmentation fault occurred and doesn't tell me where.我不确定错误发生在哪里,我尝试使用驱动程序代码在我的机器上重新创建它,但自动分级器只是说发生了分段错误,并没有告诉我在哪里。 https://imgur.com/a/W1dzI7K
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());
}
}
It seems like you forgot to zero-check product (compare it with nullptr ) before calling its method在调用其方法之前,您似乎忘记对产品进行零检查(将其与nullptr进行比较)
product->getID();
in在
Store::getProduct()
Obviously, calling a method by a zero-initialized pointer isn't a good idea.显然,通过零初始化指针调用方法不是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.