Monday, 23 April 2012

Deleting objects through pointer to void

An object of type T stored in dynamic memory (heap) can be safely deleted through pointer of type void* only if T is a POD type.

POD types are:

  • scalar types
  • POD classes
  • arrays of such types and
  • cv-qualified versions of these types

where

Scalar types are:

  • arithmetic(fundamental) types (like bool, char, int, float, double,...)
  • enumeration types
  • pointer types
  • pointer to member types
  • std::nullptr_t
  • cv-qualified versions of these types

Example 1: int is a POD type


Example 2: struct B is a POD type


Example 3: struct C is not a POD type

Memory leak is reported in debug output window when running Example 3:
Detected memory leaks!
Dumping objects ->
{144} normal block at 0x00595580, 4 bytes long.
Data: < > 01 00 00 00
Object dump complete.

This last example yields memory leak because delete applied to void* pointer freed memory allocated for C members but it did not call C destructor thus leaving memory pointed by p_ allocated.

1 comment:

micheal pan said...

BE SMART AND BECOME RICH IN LESS THAN 3DAYS....It all depends on how fast 
you can be to get the new PROGRAMMED blank ATM card that is capable of
hacking into any ATM machine,anywhere in the world. I got to know about 
this BLANK ATM CARD when I was searching for job online about a month 
ago..It has really changed my life for good and now I can say I'm rich and 
I can never be poor again. The least money I get in a day with it is about 
$50,000.(fifty thousand USD) Every now and then I keeping pumping money 
into my account. Though is illegal,there is no risk of being caught 
,because it has been programmed in such a way that it is not traceable,it 
also has a technique that makes it impossible for the CCTVs to detect 
you..For details on how to get yours today, email the hackers on : (
atmmachinehackers1@gmail.com ). Tell your 
loved once too, and start to live large. That's the simple testimony of how 
my life changed for good...Love you all ...the email address again is ;
atmmachinehackers1@gmail.com