嘿家伙我试图运行这段代码,但当编译器进入类函数时出现段错误。分段错误(核心转储)链表
这是主要的功能:
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;
};
在类的其他功能类似于这两个,所以他们都会有相同的错误。 主函数运行正确,但是当我在主函数中调用类函数时,我得到了分段错误。
你没有显示你在哪一行得到了段错误 - 但是'createMemory'函数肯定是错误的('temp-> next'没有指向分配和初始化的内存) – UnholySheep
实际上有定义的节点,但是没有头的声明 – MateuszL
忘了说吧。我该如何改变,以指向已初始化的内存?或者我如何初始化内存? –