简体   繁体   中英

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. 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().

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

//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

    product->getID();

in

    Store::getProduct()

Obviously, calling a method by a zero-initialized pointer isn't a good idea.

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