C + + memory allocation (new and delete)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.