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.