Item 50 reload new and delete

Source: Internet
Author: User

Purpose of reloading new and delete:
● Monitor memory usage.
1> there is no one-to-one relationship between new and delete. New has more memory leakage, while Delete has more, leading to undefined behavior. In this case, a new with log is required.
2> overrun and underrun. When writing data to the memory, it is written outside the buffer zone. In this case, you need to apply for a slightly larger space storage flag.
● Improve Memory Allocation Efficiency
● Memory usage statistics

The following is an example of overrun/underrun Detection:

Static const int Signature = 0 xdeadbeef; <br/> typedef unsigned char byte; <br/> void * operator new (STD: size_t size) Throw (STD: bad_alloc) <br/>{< br/> using namespace STD; <br/> size_t realsize = size + 2 * sizeof (INT ); // apply for more space <br/> void * pmem = malloc (realsize); <br/> If (! Pmem) <br/> throw bad_alloc (); <br/> // write the flag before and after the memory block <br/> * (static_cast <int *> (pmem )) = signature; <br/> * (reinterpret_cast <int *> (static_cast <byte *> (pmem) + realsize-sizeof (INT) = signature; <br/> // return available memory address <br/> return static_cast <byte *> (pmem) + sizeof (INT); <br/>}

 

Question about this Code:
1> NO new_handler
2> Data Alignment

C ++ requires that the addresses returned by operator new be aligned based on the data type. There is no problem with the memory returned by using malloc, but it is no longer the case after adding our signature. This may cause program crashes or slows down.

Necessity of rewriting new/delete:
1> Some compilers have their own debug and log versions of new/delete
2> refer to the open source memory manager, such as the boost pool.

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.