当我尝试运行程序时出现Segmentation Fault。有人可以帮我找出我做错了吗?
用这个编译:
g++ sms_out.cpp -o sms_out
g++ -c -fPIC SMSDispatch.cpp
g++ -shared SMSDispatch.o -o libSMSDispatch.so
它应该是一个共享库和动态链接。我尝试运行sms_out时出现Segmentation Fault。
// sms_out.cpp
#include <iostream>
#include<cstdlib>
#include<fstream>
#include<sstream>
#include<string>
#include "SMSDispatch.h"
using namespace std;
string sms = "";
void sendSMS(string sms)
{
SMSDispatch* sPtr=0;
sPtr->sendSMS(sms);
}
int main(int argc, char *argv[])
{
if(argv[1])
{
string input = argv[1];
string test = "--author";
if(input == test)
{
cout << "s149113" << endl;
return 0;
}
}
string line = "";
string file = "sms_out.txt";
ifstream myfile(file.c_str());
while(getline(myfile, line))
{
string idnr, landcode, number, error;
istringstream linestream(line);
unsigned short errorcode;
//Split the sentence
getline(linestream, idnr, '\t');
getline(linestream, landcode, ':');
getline(linestream, number, '\t');
getline(linestream, error);
if(idnr == "") break;
//Make string to int
try
{
errorcode = atoi(error.c_str() );
}
catch (exception &)
{
}
//Put together landcode and tlfnumber
string nr = landcode + number;
string txt = "Thank you for your vote!";
if(errorcode == 100) txt = "Invalid question, please try again";
else if(errorcode == 110) txt = "Sorry, only one vote pr. number";
else if(errorcode == 200) txt = "Invalid alternative, please try again";
else if(errorcode == 300) txt = "Missing a statement after other, please try again";
else if(errorcode == 999) txt = "An error occurred, please try again";
sms += "{\"ID\":" + idnr + ",\"nr\":" + nr + ",\"txt\":" + "\"" + txt + "\"" + "}\n";
}
cout << sms << endl;
sendSMS(sms);
}
// SMSDispatch.h
#include <string>
#ifndef SMSDISPATCH_H
#define SMSDISPATCH_H
using namespace std;
class SMSDispatch{
public:
virtual void sendSMS(string json);
};
#endif
// SMSDispatch.cpp
#include <iostream>
#include <fstream>
#include "SMSDispatch.h"
using namespace std;
/*virtual*/void SMSDispatch::sendSMS(string json)
{
ofstream myfile;
myfile.open ("sms_out.log");
myfile << json;
myfile.close();
}
int main()
{
}
答案 0 :(得分:9)
取消引用NULL
指针会导致分段错误:
void sendSMS(string sms)
{
SMSDispatch* sPtr=0;
sPtr->sendSMS(sms);
}
我看不出使用动态分配对象的原因,因此建议更改为:
void sendSMS(string sms)
{
SMSDispatch sPtr;
sPtr.sendSMS(sms);
}
答案 1 :(得分:3)
在sms_out.cpp的sendSMS
函数中,声明一个指针并将其初始化为null-poiter(0
)。下一行尝试通过该指针访问对象并调用成员函数。由于指针为空(这意味着它不指向有效对象),此操作将失败,因为seg.fault
void sendSMS(string sms)
{
SMSDispatch* sPtr=0; // this sets pointer to null
// assign the address of a valid `SMSDispatch` object instead
sPtr->sendSMS(sms);
}
要修复它,最好需要一个这种类型的实例。
根据您的需要,您可以
SMSDispatch dp; sPtr=&dp;
或sptr=new SMSDispatch;
在第一种情况下,你也可以这样做
SMSDispatch dp;
dp.sendSMS(sms);
在secons案例中,您需要在不再需要该对象后调用delete sptr;
。
另外,请注意,为了编译程序,编译器将需要SMSDispatch::sendSMS
函数的定义。通过包含SMSDispatch.h标头,您只提供声明。
你需要
-lSMSDispatch
添加到g ++选项来再次链接共享库