大家好,我正在尝试运行这段代码,但当编译器获取类函数时出现段错误。
这是主要功能:
int main (int argc, char* argv[]){
cout<<"\t1.Add Program\n";
cout<<"\t2.Kill Program\n";
cout<<"\t3.Fragmentation\n";
cout<<"\t4.Print Memory\n";
cout<<"\t5.Exit"<<endl;
LinkedList Memory;
Memory.createMemory(); (I get the segmentation error on this line)
int choice;
cin>>choice;
cout<<"choice - "<<choice<<endl;
if (choice==1){
string programName;
cin>>programName;
cout<<"Program name - "<<programName<<endl;
int size;
cin>>size;
cout<<"Program size (KB) - "<<size<<endl;
int numpages;
if (size%4==0) numpages=size/4;
if (size%4!=0) numpages=size/4+1;
Memory.addProgram(numpages, programName);
return 0;
}
这是类
class LinkedList{
private:
struct node{
string name;
node *next;
};
public:
void createMemory();
void addProgram(int val, string s);
void killProgram(string s1);
void print();
void fragmentation();
LinkedList(){head=NULL;};
};
这是两个类函数
void LinkedList::createMemory(){
int i=0;
node* temp;
temp = new node;
while(i<32){
temp->name="Free";
temp=temp->next;
i++;
}
};
void LinkedList::addProgram(int val, string s){
int i=0;
node* temp;
temp=new node;
while(temp->name!="Free")
temp=temp->next;
while(temp->name=="Free"){
while (i<val){
temp->name=s;
temp=temp->next;
i++;
}
}
cout<<"Program "<<s<<" added successfully: "<<val<<" page(s) used."<<endl;
};
该类中的其他函数与这两个函数类似,因此它们都会出现相同的错误。 主函数运行正常,但是当我在主函数中调用类函数时出现段错误。
最佳答案
while(i<32){
temp->name="Free";
temp=temp->next;
i++;
}
在此代码段中,您使用 null 或未初始化的 temp->next
也许您的代码中存在更细微的错误。使用调试器。
Tip 始终牢记在心:在构造函数中初始化所有成员,而不仅仅是选定的成员。 在我的代码中,我也为结构使用构造函数(有些人不这么建议)
关于c++ - Segmentation Fault(core dumped)链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42852639/