[英]How to correct a segmentation fault?
我不斷收到錯誤分段錯誤(核心已轉儲),因此我運行了valgrind。 這是我第一次使用它,所以不確定如何使我的代碼正常工作。 我曾嘗試更改它,但它仍然顯示核心已轉儲,或者我收到的錯誤比以前更多。 我曾嘗試使用gdb調試代碼,但調試器無法正常工作。
和相應的產品
#ifndef GS_PRODUCT
#define GS_PRODUCT
#include <iostream>
#include <string>
using namespace std;
class Product
{
private:
int plu_code;
string name;
double price;
bool by_weight;
double inventory;
public:
Product(int p_code = 0, string p_name = "", bool p_by_weight = true, double p_price = 0.0, double p_inv = 0.0);
bool sold_by_weight(void);
double compute_cost(double weight_or_unit);
string get_name(void);
int get_plu_code(void);
double get_price(void);
double get_inventory(void);
};
#endif
這是我的產品。cpp:41
#include <iostream>
#include <string>
#include "product.h"
using namespace std;
Product::Product(int p_code, string p_name, bool p_by_weight, double p_price, double p_inv)
{
plu_code = p_code;
name = p_name;
by_weight = p_by_weight;
price = p_price;
inventory = p_inv;
}
bool Product::sold_by_weight(void)
{
return by_weight;
}
double Product::compute_cost(double weight_or_units)
{
inventory -= weight_or_units;
return weight_or_units * price;
}
string Product::get_name(void) {
return name;
}
int Product::get_plu_code(void) {
return plu_code;
}
double Product::get_price(void) {
return price;
}
double Product::get_inventory(void) {
return inventory;
}
這是我的主程序商店
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>
#include "product.h"
#include "Tokenizer.h"
#include "LookupTable.h"
using namespace std;
LookupTable<Product *> table;
int numProducts = 0;
void checkout()
{
}
int main()
{
int plu;
string name;
int weight;
double inv;
double price;
table.addRange(0, 9999);
table.addRange(90000, 99999);
// std::string line;
//Input file
ifstream infile("inventory.csv");
if(infile.fail())
perror("Could not open file ");
stringstream ss;
while(infile.good())
{
string line = "";
//read a product info from file
getline(infile, line);
Tokenizer tok(line, ",");
ss<<line;
//string token = tok.next();
ss >> plu >> name >> weight >> price >>inv;
table[plu] = new Product(plu, name,weight, price,inv);
numProducts++;
}
infile.close();
checkout();
ofstream outfile;
outfile.open("output.csv");
for(int i=0; i< numProducts; i++)
{
outfile<< table[i]-> get_plu_code() << "" << table[i]->get_name()<<""<<table[i]->sold_by_weight() <<""<<table[i]->get_price() <<""<<table[i]->get_inventory();
}
outfile.close();
return 0;
}
分段錯誤的含義是您嘗試訪問的頁面不具有操作所需的權限(通常為讀/寫權限,但也可能具有可執行權限)。 也就是說,系統告訴您您嘗試訪問的內容不是真正存在的或無法訪問的。
有許多典型的問題最終導致分割錯誤。 以下是其中一些:
要獲得有關實際細分錯誤的幫助,您需要提供一個簡短但完整的示例來展示問題。 引用一些您認為與問題相關的行通常不太可能實際包含實際問題。
您似乎沒有從Product :: get_inventory()返回的任何價值庫存。 我認為這要么無法編譯,要么您有一些未顯示的相關代碼。 后者很可能是這種情況,並且變量清單在返回時尚未初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.