【C++】关于new分配空间
1如果不使用new,则在函数结束时内存被回收,指针变成野指针
#include <iostream> using namespace std; struct Node { int val; Node *next; Node(int v=0,Node * n=NULL){ val=v; next=n; } }; Node * head; void fun(){ Node t(1); head=&t; cout<<"head"<<head->val<<" "<<head->next<<endl; } int main(){ fun(); cout<<"head"<<head->val<<" "<<head->next<<endl; return 0; }
执行完成,耗时:0 ms head1 0 head54732392 0x7fc624c80649
2如果使用new,则必须使用delete才能回收内存
#include <iostream> using namespace std; struct Node { int val; Node *next; Node(int v=0,Node * n=NULL){ val=v; next=n; } }; Node * head; void fun(){ head=new Node(1); cout<<"head"<<head->val<<" "<<head->next<<endl; } int main(){ fun(); cout<<"head"<<head->val<<" "<<head->next<<endl; delete head; return 0; }
执行完成,耗时:4 ms head1 0 head1 0