Unintentional Memory leakage when the C ++ object array is released

Source: Internet
Author: User

The greatest enemy of mankind is forgetting. --- Lazy voice

This problem is easy to find, because it is a typical issue.

For example:

I,

Object is a class,

Object * object = new object [3];

... Balabala...

Delete object; // Problem

At this time, memory leakage is triggered, because only the memory of the object [0] is released (the compiler calls the Destructor once with the address of & object [0 ),

Equivalent to delete [1] object;

The correct release should be Delete [] object;

Or delete [3] object;

2. Complicated

Object is a class,

Object ** object = new object * [3]; // only a pointer array of three object objects is dynamically allocated, but they are not objects themselves.

// Allocate

For (INT I = 0; I <3; ++ I)

{

Object [I] = new object ();

}

... Balabala...

Delete [] object; // Problem

In fact, this also causes memory leakage. In this case, delete is only a pointer rather than an object to which it points.

To do this, you can:

For (INT I = 0; I <3; ++ I)

{

Delete object [I];

}

Delete object;

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.