New dynamically allocated Delete frees memory

Source: Internet
Author: User

In C + +, for variables and objects are compiler-allocated at compile-time, for array initialization, can not determine how much memory, it is very likely to cause large open small use case.

New Dynamic Assignment

General format: 1. Pointer variable name =new type identifier;

2. Pointer variable name =new type identifier (initial value);

3. Pointer variable name =new type identifier [number of memory units]; Defining methods for opening arrays

The new operator returns a pointer to a variable of the assigned type.

Delete Frees memory

General format: 1.delete p;

2.delete []p;

Delete the address space of the variable p and release the int memory. --Heap area (priority queue) Delete P is actually meant to remove the target address that P points to, freeing up the memory it occupies, rather than removing the P pointer.

There are two major problems with delete: 1. Memory leaks 2. Repeat release

int* P=new int;

Delete p;

P=null; A good habit of washing your hands after the toilet

Destructors

Destructors for linear tables

1. int* p;

while (Fisrt!=null) {

P=first;

first=first->next;

Delete p;

}

Error Resolution:

int* P=first;

while (P!=null) {

Delete p;

p=p->next;

}

Has released the first address pointed to by P, what exactly does P->next point to? Error!!!

int a=5;

int* P=a;

cout<<*p<<endl; Address content to which P is pointing

cout<<&p<<endl; Address of P itself

cout<<p<<endl; P point to address = = &a

New dynamically allocated Delete frees memory

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.