函数返回指针 c++ 导致的分段错误

Segmentation fault caused by function returning pointer c++?

本文关键字:分段 错误 返回 指针 c++ 函数      更新时间:2023-10-16

这个函数非常混乱,它会导致我的测试仪出现分割错误,有什么办法可以改进它吗? 它应该采用 SKU 参数,它是 Product 对象的属性,并将其与库存数组中的元素(由指向 Product 的指针组成,大小为 50)匹配,如果找到我应该返回指针。

Product* Supplier::getProduct(const string &sku)
{
bool found = false;
int counter =0;
Product* ret= new Product();
        while (found =false && counter< inventory.size())
        {
                if(inventory[counter] && sku == inventory[counter]->getSKU())
                {
                        found = true;
                        ret = inventory[counter];
                }
        counter++;
        }
        if (found ==false)
        {
                cout << "not found" << endl;
        }
return ret;
}

你有代码found = false .这需要found == false!found

更改:

    while (found =false && counter< inventory.size())

    while (found==false && counter< inventory.size())