Dynamic memory Management in C + +

Source: Internet
Author: User


Dynamic memory management issues in C + +

use new and delete in C + + for dynamic memory management. New and delete implement dynamic management objects, new[] and delete[] to implement dynamic management object arrays. Both the new and delete operators in C + + use the malloc and delete functions we have learned from C to implement dynamic memory.


First, a brief introduction of several dynamic memory function malloc,realloc,calloc,free in C;

void *malloc (size_t size); Dynamic Memory Opening function


void free (void *pointer); Memory deallocation function, passing a null to the pointer will have no effect


void *relloc (void *ptr,size_t,new_size);//expansion function, still save the content before expansion (enlarge memory), if the memory is reduced, the memory block end of the space is taken away


void *calloc (size_t num_elements,size_t size);//dynamic memory is opened and initialized, and the returned pointer points to the contents of the memory initialized to 0




generally in the program memory error is likely to be the release of dynamic memory problems, so when using dynamic memory must pay attention to the issue of release, in c also need to be aware of the dynamic memory after releasing the pointer to dynamic memory NULL, avoid the formation of wild pointers, Okay, dynamic memory management in C is the memory of this, after all, I want to say is C + + dynamic memory management problems. 650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0057.gif "alt=" J_0057.gif "/>


C + + using New/delete or new[]/delete[] to achieve dynamic management, in particular, should be reminded that in the dynamic memory management must pay attention to the New/delete,new[]/delete[],malloc/free must pay attention to match use.


I know you're going to want it. Since C + + is compatible, why not use Malloc/free in C directly, but to use new/delete, first we need to understand the difference between the two and contact.


"What are the differences and connections between Malloc/free and New/delete?"

1. They are all portals for dynamic management of memory.

2. Malloc/free is a C/C + + standard library function, and new/delete is a + + operator.

3. Malloc/free only dynamically allocates memory space/frees space. New/delete, in addition to allocating space, calls constructors and destructors for initialization and cleanup of objects (cleanup members).

4. Malloc/free needs to manually calculate the type and the return value void*,new/delete the number of bytes that can automatically calculate the type of memory, returning a pointer of the corresponding type.


Write a simple program that shows the use of malloc and new;


First define an array class:


Class Array

{

Public

Array (size_t size = 10)

: _size (size)

, _a (0)

{

cout << "Array (size_t size)" << Endl;

if (_size > 0)

{

_a = new Int[size];

}

}

~array ()

{

cout << "~array ()" << Endl;

if (_a)

{

Delete[] _a;

_a = 0;

_size = 0;

}

}

Private

Int*_a;

size_t _size; Record dynamic space opens up several types of int space

};

Below we observe the use of new and malloc

void Test ()

{

array* P1 = (array*) malloc (sizeof (Array)); malloc () is responsible only for the opening up of space

array* P2 = new Array; New opens up space and constructs an object

array* p3 = new Array (20);

array* P4 = new ARRAY[10];

Free (p1);

Delete P2;

Delete P3;

Delete[] P4; Be sure to use delete[when releasing the dynamically opened array space]

}

By testing the program, it is clear that the difference between new and malloc is seen.



In fact, using delete from the dynamically opened array space does not necessarily make an error, for example:

int *pi = new INT[10];

Delete pi;

at this point, the program does not go wrong, the program does not crash does not mean that the program is correct, but in this operation did not crash, I believe everyone can see that at this time the delete is not the dynamic open space all released, only the space of an element of the array is released, there is a serious memory leak problem, Many people may not pay attention to the problem of memory leak, but this problem is also fatal, memory leak is not only to drain the system memory, the most important problem you are running the program may crash, which is fatal to a program, but this problem is the problem that every programmer is vexed, Memory leaks in the program development is always the same, to solve this problem is to use the knowledge of smart pointers, this is not the focus of my blog, we are still quiet to study New/delete Bar!!!!



It has been said that the internal of the new and delete in C + + is also dependent on malloc/free implementation, when using our new we debug into internal discovery, new called Operator new (), delete called operator delete (), C + + There are several other memory management interfaces, and the implementation of the NEW/DELETE expression relies on these functions in the library.

void * operator new (size_t size);

void operator Delete (size_t size);

void * operator new [] (size_t size);

void operator delete[] (size_t size);

These functions implement space creation and release internally, they only take responsibility for the opening and release of space, do not call constructors to construct objects, and do not call destructors to clean objects. In fact they are just malloc/free packages.


Below we summarize the next new/delete,new[]/delete[] what to do in the program run separately



New has done two things.

1. Tune operator new to allocate space.

2. Tune the constructor to initialize the object.

Delete has done two things.

1. Destructor Cleanup Object

2. Tune operator Delete to free up space

New[n]

1. Tune operator new to allocate space.

2. Adjust the n-th constructor to initialize each object separately.

Delete[]

1. Tune the n-th destructor to clean up the object.

2. Adjust operator delete to free up space.


It is particularly important to note that delete[] called n this destructor, where n is saved?

Actually new[] opened up four bytes to hold the number of objects created when calling operator[].


Number of Objects 9
Pointer to Object
Pointer to Object Pointer to Object Pointer to Object Pointer to Object Pointer to Object Pointer to Object Pointer to Object Pointer to Object

Four bytes


We can use the positioning new expression to simulate the implementation of the new function, let us first understand the following new expression:

The position new expression is called by the constructor to initialize an object in the allocated raw memory space.

New (place_address) type

New (place_address) type (initializer-list)

Place_address must be a pointer, initializer-list is the initialization list of the type.

Analog implementation new[]/delete[]


There is a memory alignment for member variables in Class A//classes

{

Public

A (int size = 10):

_SZ (size)

, _p (new Int[size])

{}

A (const a& a):

_SZ (A._SZ)

, _p (new INT[A._SZ])

{

}

~a ()

{

Delete[] _p;

}

Private

int _SZ;

int *_p;

};


void Test ()

{

A *a = (A *) operator new[] (sizeof (a) *10 + 4);

To open up space for the class, since the destructor display definition, more than four bytes to save the number of objects

* (int *) A = 10;

A *pstart = (A *) ((int*) a + 1);

int i = 0;

for (i = 0; i < 10;i++)

{

New (Pstart+i) A (i);

}

int count = * ((int*) pStart-1);

for (i = 0; i < count; i++)

{

Pstart[i].~a ();

}

Operator delete[] ((int*) pStart-1);//Free space

}

New/delete, new[]/delete[] implementation in the program:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/7E/6E/wKiom1b-p3TDDNzTAACGVxQW9rE423.png "title=" QQ picture 20160402005232.png "alt=" Wkiom1b-p3tddnztaacgvxqw9re423.png "/>

The red font in this article is the focus.


I see still owe, if there is misunderstanding of the place, but also hope that the great God put forward, I must be open-minded to learn, and seriously correct.

This article is from the "Qin-wang" blog, make sure to keep this source http://10810196.blog.51cto.com/10800196/1759454

Dynamic memory Management in C + +

Related Article

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.