In C, malloc and free are functions that are included in the Stdlib.h header file, and the assignment succeeds in returning the pointer, failing to return a null pointer.
The difference from new is:
1,malloc and free are standard library functions for c++/c languages, and new/delete are operators of C + +. They can all be used to request dynamic memory and free memory.
3, so the C + + language requires an operator new that can perform dynamic memory allocation and initialization, with an operator delete that can perform cleanup and release of memory work. Note New/delete is not a library function.
4,c++ programs often call C functions, whereas C programs can only use Malloc/free to manage dynamic memory.
(Excerpt from http://zhidao.baidu.com/link?url=IrwYsOm_ykBlbfF3DCsfeKwNj2bfwahMKa501_ Hs7cgrrnk5daeu11devgzhpwv9nsflmwlx6bp14bjunb-exa)
The code uses the following:
1#include <iostream>2#include <fstream>3#include <stdlib.h>4 #defineMaxnum 2005 intIsood (intn);6 7 using namespacestd;8 9 Ten intMainvoid) One { A intN; -cout<<"Input N:"; -Cin>>N; the - int*p; -P= (int*)malloc(nsizeof(int)); - for(intI=0; i<n;i++) + { -p[i]=i; + } A for(intI=0; i<n;i++) at { -cout<<p[i]<<" "; - } - - Free(p); -}
#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);d elete [] q;}
C + + memory allocation (new and delete)