-1
這個功能非常混亂,它會在我的測試儀上導致分段錯誤,有什麼方法可以改善它嗎?它應該採用sku參數,它是Product對象的一個屬性,並將其與庫存數組中的元素(其中包含指向Product的指針並且大小爲50)匹配,如果發現我應該返回指針。函數返回指針C++導致的分割錯誤?
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;
}
而(發現= FALSE ..)應同時(發現==假的...) – Inisheer
你的內存泄漏。您創建一個'產品'的實例,但是當在庫存中找到一個項目時它永遠不會被刪除。 –
爲什麼不徹底擺脫'found',一旦找到它就返回結果?並擺脫那個'新';它導致內存泄漏。返回'nullptr',或者拋出異常,如果沒有找到。 –