C ++ memory allocation (new and delete), newdelete
In c, malloc and free are functions, which are included in the stdlib. h header file. If the allocation is successful, a pointer is returned. If the allocation fails, a null pointer is returned.
The difference with new is:
1. malloc and free are standard library functions of C ++/C, and new/delete are operators of C ++. They can be used to apply for dynamic memory and release memory.
2. For non-Internal data objects, the use of maloc/free alone cannot meet the requirements of dynamic objects. The constructor must be automatically executed when the object is created, and the Destructor must be automatically executed before the object is extinct. Since malloc/free is a library function rather than an operator and is not controlled by the compiler, it is impossible to impose the tasks of executing constructor and destructor on malloc/free.
3. Therefore, the C ++ language requires a new operator that can complete dynamic memory allocation and initialization, and a delete operator that can clean up and release memory. Note that new/delete is not a database function.
4. C ++ programs often call C functions, while C Programs can only use malloc/free to manage dynamic memory.
(From the http://zhidao.baidu.com/link? Url = IrwYsOm_ykBlbfF3DCsfeKwNj2bfwahMKa501_hS7cgrrNk5DAeu11devGzHpWv9NsfLmwlX6Bp14BjuNB-Exa)
The Code is as follows:
1 #include <iostream> 2 #include <fstream> 3 #include<stdlib.h> 4 #define MAXNUM 200 5 int Isood(int n); 6 7 using namespace std; 8 9 10 int main(void)11 {12 int n;13 cout<<"input n:";14 cin>>n;15 16 int *p;17 p=(int *)malloc(n*sizeof(int));18 for(int i=0;i<n;i++)19 {20 p[i]=i;21 }22 for(int i=0;i<n;i++)23 {24 cout<<p[i]<<" ";25 }26 27 free(p);28 }
#include <iostream>#include <fstream>#include<stdlib.h>#define MAXNUM 200int Isood(int n);using namespace std;int main(void){int *p=new int;int a=3;p=&a;cout<<*p<<endl;delete p;//cout<<*p;int *q=new int [3];q[0]=0;q[1]=1;*(q+2)=3;cout<<q[0]<<endl;cout<<*(q+2);delete [] q;}