C++ 在动态内存分配中获取运行时错误

C++ 在动态内存分配中获取运行时错误,c++,linked-list,runtime-error,dynamic-memory-allocation,C++,Linked List,Runtime Error,Dynamic Memory Allocation,程序应该像操作系统那样分配内存 这是主要功能 int main (int argc, char* argv[]){ string command; if(argc==2) command = argv[1]; else cout<<"Not enough commands"<<endl; if (command.compare("best")) cout<<"Using best fit algorithm"<<

程序应该像操作系统那样分配内存

这是主要功能

int main (int argc, char* argv[]){
  string command;

 if(argc==2)
      command = argv[1];

 else cout<<"Not enough commands"<<endl;

 if (command.compare("best"))
     cout<<"Using best fit algorithm"<<endl;

 if (command.compare("worst"))
     cout<<"Using worst fit algorithm"<<endl;

 cout<<"\t1.Add Program\n";
 cout<<"\t2.Kill Program\n";
 cout<<"\t3.Fragmentation\n";
 cout<<"\t4.Print Memory\n";
 cout<<"\t5.Exit\n";

 LinkedList Memory;
 Memory.createMemory();

 int choice;
 cin>>choice;
 cout<<"choice - "<<choice<<endl;

 if  (choice==1){
     string programName;
     cin>>programName;
     cout<<"Program name - "<<programName<<endl;
     int si;
     cin>>si;
     cout<<"Program size (KB) - "<<si<<endl;
     Memory.addProgram(si, programName);
 }
 if  (choice==2){
     string programName;
     cin>>programName;
     cout<<"Program name - "<<programName<<endl;
     Memory.killProgram(programName);
 }
 if  (choice==4){
     Memory.print();
 }
 if  (choice==5){
     return 1;
}
return 0;
}
intmain(intargc,char*argv[]){
字符串命令;
如果(argc==2)
command=argv[1];

否则不能将成员
LinkedList::head
初始化为空指针

然后在
LinkedList::createMemory
中执行
node*temp=head
操作,使
temp
成为空指针

最后,在
createMemory
中的循环中,您执行
temp->name=“Free”
操作,该操作会取消对空指针的引用,并导致未定义的行为和很可能的崩溃

如果希望列表中有32个预先分配的节点,那么实际上应该为这些节点分配内存

LinkedList memory;
memory.createMemory();
此代码可能是您的错误源。内存还没有任何值,因此当您尝试访问内存中的函数“createMemory”时,会出现空指针错误。

一般来说,当你问问题时,试着提供更多信息。如果你添加了你得到的错误、它发生在哪一行、错误消息或类似的内容,这个问题会更清楚。

当你调用
Memory.createMemory();
时,这个程序会崩溃。 由于您没有在函数
createMemory()
中为
temp
分配内存,
temp
指向NULL,因此
temp->name=“Free”
将使您的程序崩溃。您应该使用
new
temp
分配内存。您应该尽力帮助您

顺便说一句,您处理命令参数的方式不合适,如果用户输入超过2个参数,并且您告诉用户
没有足够的命令
,该怎么办

if(argc==2)
  command = argv[1];
else cout<<"Not enough commands"<<endl;
if(argc==2)
command=argv[1];

else coutIt没有给我一个具体的错误,它只是说program2.exe停止工作,然后崩溃。这很不寻常。你用什么来执行代码?我希望它能打印错误消息,但我没有任何代码块的经验,所以我会听从更有知识的人。@Matteo怎么样
head=temp=new node
?所以声明temp为指向节点的指针,然后写入head=temp=new node这是分配它的正确方法node*temp;temp=new node;是的,它是正确的。但是我认为你确实需要检查以了解更多关于动态内存@MatteoI的信息。我阅读了网站,然后运行了调试器,但我仍然不明白为什么它给出的错误是temp->name=“Free”,因为temp指向NULL,这表示什么都没有。当你从空中请求字符串“Free”时,程序将崩溃。@Matteo
if(argc==2)
  command = argv[1];
else cout<<"Not enough commands"<<endl;